The correct answer is
A1B0A0B1A0B2 (which I checked to be true)
but what I was thinking is
A1B0A1B1A1B2
My question more specifically is that why after Line 3 gets executed, a1.name = A0. Shouldn't it remain the previous value of "A1" ???
Hi Roopesh,
U try to observe one thing in the above code.Can u have look at the line //2 & //3?.Do u find any difference between those two stmts?.Yes there is.
void m1() {new A().new B();} In the above method, after invoking method m1 using an instance of A(with name A0) one more new instance is created whose name is set to A1.
Now instance of B is created using this instance(with name A1) so the output after this method call is A1B0.
void m2() {this.new B();}// 3 In the above method,after invoking method m1 using an instance of A(with name A0) u can observe no new instance of A is created and also new instance of B is created using an already existing instance of A(with name A0.Yes "this" in the above stmt refers to the instance "A0" only not "A1").So the output is A0B1.
void m3() {new B();}// 4 Similarly in the above line //4 also the stmt would be expanded as this.new B()by the compiler(i.e., will be executed as this.new B().even though "this" reference is not explicitly mentioned by you) & it gets executed.Hence the output is A0B2.
So the final output is A1B0A0B1A0B2.
Hope it helps!!.
Regards,
Priya.