Consider:
class TestParent{
public int i = 100;
public void printName(){
System.err.println(this); //{TestChild@428} according to the Debugger.
System.err.println(this.i); //this.i is 100.
}
}
class TestChild extends TestParent{
public int i = 200;
}
public class ThisTest {
public static void main(String[] args) {
new TestChild().printName();
}
}
I know that similar questions have been asked, but I couldn't get a firm understanding of the 'this' variable in Java.
Let me try to explain how I understand the result of the above image.
Since it's a
new TestChild()
object that's calling theprintName()
method, thethis
variable in line 6 is set to aTestChild
object - {TestChild@428} according to the Debugger.However, since Java doesn't have a virtual field - I'm not completely sure what this means, but I conceptually understand it as being the opposite of Java methods, which support Polymorphism -
this.i
is set to 100 ofTestParent
at compile time.So no matter what
this
is,this.i
in aTestParent
method will always be thei
variable in theTestParent
class.
I'm not sure that my understanding is correct so please correct me if I'm wrong.
And also, my main question is,
How is the this
variable set to the current object that's calling the method? How is it actually implemented?