JAVA里面内部类的创建是如何完成的呢?我们可以使用.this和.new两个关键字进行完成:
-
在外部类中使用.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();
}
}