使用 outerClass.this 从内部 class 访问外部 class

Accessing outer class from within inner class using outerClass.this

非静态内部 class 对外部 class 的所有常规成员具有完全可访问性。但是还有另一种方法可以使用 (outerClass.this.regularMember).. 访问这些成员,请查看以下代码:

public class Car {
  int x = 3;
  public static int hp =6;
  public void move()
  {
    System.out.println(hp);
  }

  public  class Engine{
     public int hp =5;
     public int capacity; 
     public void start()
     {
        Car.this.move(); // or we can use only move();
     }

  }
}
  1. 如果使用 Car.this.move();move();
  2. 之间存在任何实际差异,请您解释一下
  3. 你如何解释 Car.this. 的语法,据我所知 this 这里指的是一个Type Engine 的对象 但是如果我使用另一个引用说 Engine smallEngine = new Engine(); 那么 this 关键字不能被 [=19= 替代]小引擎。
  1. 如果您的 Engine class 有一个 move 方法,那么 move() 将不同于 Car.this.move().

  2. this表示当前实例。当你想引用外部 class 时,你可以用外部 class 限定 this 关键字来引用外部 class 的实例。重要的是要记住 Engine 的实例(因为它不是静态的)总是伴随着 Car 的实例,所以你可以参考它。

您不能说 OuterClass.smallEngine.move(),因为这会与访问 OuterClass.

的静态 public 字段的语法冲突

如果OuterClass有这样的字段:

 public static String smallEngine;

...那么上面的语法就会有歧义。由于 this 是一个关键字,您不能有一个名为 this 的字段,因此语法 OuterClass.this 永远不会有歧义。