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)
  }
} ///:~

 

转载于:https://www.cnblogs.com/jiangfeilong/p/10219490.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值