[英]Accessing outer class from within inner class using outerClass.this
The -non-static- inner class has a full accessibility to all regular members of the outer class. -non-static-内部类具有对外部类的所有常规成员的完全可访问性。 but there is another way to access these members using the (outerClass.this.regularMember).., have a look on the following code:
但是还有另一种方法可以使用(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();
Car.this.move();
之间有任何实际区别,请你解释一下Car.this.move();
and move();
move();
Engine smallEngine = new Engine();
Engine smallEngine = new Engine();
then this keyword is not substitutable by smallEngine . If your Engine
class has a move
method, then move()
would be different from Car.this.move()
. 如果你的
Engine
类有一个move
方法,那么move()
将与Car.this.move()
不同。
this
means the current instance. this
意味着当前的实例。 When you want to refer to the outer class, you are allowed to qualify the this
keyword with the outer class to refer to the outer class's instance. 如果要引用外部类,则可以使用外部类限定
this
关键字以引用外部类的实例。 The important thing to remember is that an instance of Engine
(since it is not static) is always accompanied by an instance of Car
and so you can refer to it. 要记住的重要一点是
Engine
的实例(因为它不是静态的)总是伴随着Car
的实例,所以你可以参考它。
You are not allowed to say OuterClass.smallEngine.move()
because that would conflict with the syntax for accessing a static public field of OuterClass
. 你不准说
OuterClass.smallEngine.move()
因为这将与语法来访问的静态公共领域的冲突OuterClass
。
If OuterClass
had a field like this: 如果
OuterClass
有这样的字段:
public static String smallEngine;
...then the above syntax would be ambigious. ......那么上面的语法就会变得暧昧。 Since
this
is a keyword, you cannot have a field named this
and therefore the syntax OuterClass.this
will never be ambigious. 由于
this
是一个关键字,你不能有一个名为this
的字段,因此语法OuterClass.this
永远不会是ambigious。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.