How is the 'this' variable in Java actually set to the current object?

前端 未结 5 1928
囚心锁ツ
囚心锁ツ 2021-02-03 21:19

Consider:

class TestParent{
  public int i = 100;
  public void printName(){
    System.err.println(this); //{TestChild@428} according to the Debugger.
    Syste         


        
5条回答
  •  借酒劲吻你
    2021-02-03 22:09

    Adding some more info on top of @Tom Anderson answer, which explains hiding concept nicely.

    I have added one more constructor in Child ( TestChild) which prints values of i in both parent and child.

    If you want get value of i from child (TestChild), override the method in TestChild.

    class TestParent{
      public int i = 100;
      public void printName(){
        System.err.println("TestParent:printName()");
        System.err.println(this); //{TestChild@SOME_NUM} according to the Debugger.
        System.err.println(this.i); //this.i is 100.
      }
    }
    
    class TestChild extends TestParent{
      public int i = 200;
      public TestChild(){
        System.out.println("TestChild.i and TestParent.i:"+this.i+":"+super.i);
      }
      public void printName(){
          //super.printName();
          System.err.println("TestChild:printName()");
          System.err.println(this); //{TestChild@SOME_NUM} according to the Debugger.
          System.err.println(this.i); //this.i is 200.
      }
    }
    
    public class ThisTest {
      public static void main(String[] args) {
        TestParent parent = new TestChild();
        parent.printName();
      }
    }
    

    Case 1: If I comment super.printName() call from child, Child version of TestChild.printName() prints the value of i in TestChild

    Output:

    TestChild.i and TestParent.i:200:100
    TestChild:printName()
    TestChild@43cda81e
    200
    

    Case 2: TestChild.printName() calls super.printName() as the first line in printName() method. In this case, i value from both parent and child are displayed in respective methods.

    Output:

    TestChild.i and TestParent.i:200:100
    TestParent:printName()
    TestChild@43cda81e
    100
    TestChild:printName()
    TestChild@43cda81e
    200
    

提交回复
热议问题