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

前端 未结 5 1930
囚心锁ツ
囚心锁ツ 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

    To directly address what you see in the output: The call to print 'this.i' is passing as argument to 'print()' the value of the field 'i' in the current scope, which is the scope of the parent class. By contrast, the call to print 'this' is getting translated under the hood to a call to print 'this.getClass().getName()' [roughly speaking], and the 'getClass()' call gets the actual class object, which is for the child class.

提交回复
热议问题