简体   繁体   English

使用outerClass.this从内部类中访问外部类

[英]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();
     }

  }
}
  1. Could you please explain me if there would be any practical difference between using Car.this.move(); 如果使用Car.this.move();之间有任何实际区别,请你解释一下Car.this.move(); and move(); move();
  2. How can you explain this syntax of Car.this. 你怎么解释Car.this的这种语法 , cause as far as I understand this here refers to an object of Type Engine but then if I used another reference say by doing Engine smallEngine = new Engine(); ,导致据我了解这里指的是发动机类型对象 ,但这时如果我用另一个参考做说Engine smallEngine = new Engine(); then this keyword is not substitutable by smallEngine . 那么这个关键字不能被smallEngine替代。
  1. If your Engine class has a move method, then move() would be different from Car.this.move() . 如果你的Engine类有一个move方法,那么move()将与Car.this.move()不同。

  2. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM