Lets see what would happen when an object of foo
is created.
foo x = new foo();
On encountring new
JVM will create an object of foo
in heap. Next step (Note its Next step) is constructor execution. In java object is created on heap and then constructor is invoked. This is the reason even if constructor throws an exception, even then object is created (can be reclaimed in finalize()). As object is already created and is present in heap references can refer to it.
this
is reference to the object.
Now private foo i = this;
is executed as a part of constructor (this is as per java behavior, all instance fields if initialized at the place of declaration, it is executed whenever constructor is invoked). this
already refers to the object created on heap and now i
also refers to the same Object on Heap. Once constructor is successfully executed without any exception the variable x
also refers to the same Object on heap.
So we have one object of foo
and we have references to that object as below :
this
(from within instance methods of foo
)
- we have instance vatiable
i
- and we have variable
x
as reference to that Object
Also as i
is of type foo
so it can refer to an object of type foo
and this
is also a reference of type foo
referring to an object of type foo
. Making i
equal to this
makes i
also referring to same object.
Hope this helps in clearing your doubts.