-non-static-内部类对外部类的所有常规成员具有完全可访问性。但是还有另一种使用(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();
}
}
}
您能否解释一下
Car.this.move();
和move();
之间是否有实际区别?您如何解释Car.this的语法。 ,因为据我所知,这里指的是Type Engine的对象,但是如果我使用另一个引用说做
Engine smallEngine = new Engine();
,则此关键字不能由smallEngine替代。 最佳答案
如果您的Engine
类具有move
方法,则move()
将不同于Car.this.move()
。this
表示当前实例。当您要引用外部类时,可以使用外部类来限定this
关键字,以引用外部类的实例。要记住的重要一点是Engine
的实例(因为它不是静态的)总是伴随有Car
的实例,因此您可以引用它。
您不允许说OuterClass.smallEngine.move()
,因为这将与访问OuterClass
的静态公共字段的语法冲突。
如果OuterClass
具有这样的字段:
public static String smallEngine;
...那么上面的语法将是模棱两可的。由于
this
是关键字,因此不能有一个名为this
的字段,因此语法OuterClass.this
永远不会模棱两可。