posted 20 years ago
I am not sure that I can clear your doubt, however, when I walked through the program by hand I got the same result that you indicated. (This is pretty lazy, I should run it too!)
Anyway, we start out with a static variable counter for A (static-A-counter) initialized to 0, and a static variable innerCounter for A (static-A-innerCounter) initialized to 0.
Static initialization occurs, I believe, at either the time a static method is accessed or a the class is instanced. Better look into this.
In any event, walking through the code line by line:
A a1 = new A(); // 5
At this point we have created A. The a1.name is set to A0, and then the counter is incremented to 1.
a1.m1(); // 6 - calls void m1() { new A().new B(); } //2
Now we create a new instance of A, on which we call new for B. This new instance of A I will call anonymous1. So for anonymous1, the name is set to A1, and then the static-A-counter is incremented to 2. Now we invoke the constructor on B. This sets its own name to B0, and then increments static-A-innerCounter to 1. Then it prints out "A1B0".
a1.m2(); // 7- calls void m2() { this.new B(); } //3
Okay now we have come back to A1. It still has the same name- A0. We create B on this instance. The constructor in B sets the name to B1 (the value of static-A-innerCounter) and then increments it to 2. It prints out "A0B1" (the name of a1 plus the name of the new B class.
a1.m3(); // 8 - calls void m3() { new B(); } //4
Again, we are utilizing A1. It has the name A0. We create B with this instance. The constructor in B sets the name to B2 (the value of static-B-innerCounter) and then increments it to 3. It prints out "A0B2").