java 内部类使用 .this 和 .new

如果需要生成对外部类对象的引用,可以使用外部类的名字后面紧跟圆点和this,这样产生的引用自动地具有正确的类型,这一点在编译器就被知晓并受到检查,因此并没有运行时开销

//: innerclasses/DotThis.java
// Qualifying access to the outer-class object.
package object;
public class DotThis {
  void f() { System.out.println("DotThis.f()"); }
  public class Inner {
    public DotThis outer() {
      return DotThis.this; //这里生成了类DotThis的引用(inference)
      // A plain "this" would be Inner's "this"
    }
  }
  public Inner inner() { return new Inner(); }
  public static void main(String[] args) {
    DotThis dt = new DotThis();
    DotThis.Inner dti = dt.inner();
    dti.outer().f();//这里用类DotThis的引用(inference) 创建类DotThis的对象
  }
} /* Output:
DotThis.f()
*///:~

要去创建某个内部类的对象,必须字new表达式中提供其他外部类对象的引用,这就需要.new语法,必须使用外部类的对象来创建内部类

//: innerclasses/DotNew.java
// Creating an inner class directly using the .new syntax.
package object;
public class DotNew {
  public class Inner {}
  public static void main(String[] args) {
    DotNew dn = new DotNew(); 
    DotNew.Inner dni = dn.new Inner(); //这里利用DotNEW的对象生成内部类Inner的对象
    //! DotNew.Inner dni = DotNew.new Inner(); //这样不允许(allow)
  }
} ///:~

 

posted @ 2019-01-04 13:58  江期玉  阅读(2077)  评论(0编辑  收藏  举报