内部类之.this和.new

       JAVA里面内部类的创建是如何完成的呢?我们可以使用.this和.new两个关键字进行完成:

  1. 在外部类中使用.this声明

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

//: innerclasses/DotThis.java
package innerclasses; /* Added by Eclipse.py */
// Qualifying access to the outer-class object.

public class DotThis {
  void f() { 
    System.out.println("DotThis.f()");
  }
  public class Inner {
    public DotThis outer() {
      return DotThis.this;
      // 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();
  }
} /* Output:
DotThis.f()
*///:~

2.使用.new用外部类对象创建一个内部类

      有时你可能想告知某些其他对象,去创建某个内部类的对象,要实现此目的,你必须在new表达式中提供对其他外部类对象的引用,这需要圆点和new语法.

//: innerclasses/DotNew.java
package innerclasses; /* Added by Eclipse.py */
// Creating an inner class directly using the .new syntax.

public class DotNew {
  public class Inner {
    
  }
  public static void main(String[] args) {
    DotNew dn = new DotNew();
    DotNew.Inner dni = dn.new Inner();
  }
} 

 

创建内部类的两种方法:

1.在外部类中创建一个方法,该方法返回对内部类的一个引用

2.使用.new用外部类对象创建一个内部类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值