小编Kev*_*ark的帖子

Java中的'this'变量实际上是如何设置为当前对象的?

考虑:

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();
  }
}
Run Code Online (Sandbox Code Playgroud)

我知道有类似的问题已被提出,但我无法对Java中的'this'变量有一个明确的理解.

让我试着解释一下我是如何理解上面图像的结果的.

  1. 因为它是一个new TestChild()调用printName()方法thisTestChild对象,所以根据调试器,第6行中的变量被设置为一个对象 - {TestChild @ 428}.

  2. 但是,由于Java没有虚拟字段 - 我不完全确定这意味着什么,但我从概念上理解它与Java方法相反,它支持多态性 - 在编译时this.i设置为100 TestParent.

  3. 所以不管是什么this,this.i在一个TestParent方法中总是会i …

java oop this-keyword

30
推荐指数
2
解决办法
3461
查看次数

标签 统计

java ×1

oop ×1

this-keyword ×1