🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## [使用 .this 和 .new](https://lingcoder.gitee.io/onjava8/#/book/11-Inner-Classes?id=%e4%bd%bf%e7%94%a8-this-%e5%92%8c-new) 如果你需要生成对外部类对象的引用,可以使用外部类的名字后面紧跟圆点和**this**。这样产生的引用自动地具有正确的类型,这一点在编译期就被知晓并受到检查,因此没有任何运行时开销。下面的示例展示了如何使用**.this**: ~~~ // innerclasses/DotThis.java // Accessing 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(); } } ~~~ 输出为: ~~~ DotThis.f() ~~~ 有时你可能想要告知某些其他对象,去创建其某个内部类的对象。要实现此目的,你必须在**new**表达式中提供对其他外部类对象的引用,这是需要使用**.new**语法,就像下面这样: ~~~ // innerclasses/DotNew.java // Creating an inner class directly using .new syntax public class DotNew { public class Inner {} public static void main(String[] args) { DotNew dn = new DotNew(); DotNew.Inner dni = dn.new Inner(); } } ~~~ 要想直接创建内部类的对象,你不能按照你想象的方式,去引用外部类的名字**DotNew**,而是必须使用外部类的对象来创建该内部类对象,就像在上面的程序中所看到的那样。这也解决了内部类名字作用域的问题,因此你不必声明(实际上你不能声明)dn.new DotNew.Inner。 下面你可以看到将**.new**应用于 Parcel 的示例: ~~~ // innerclasses/Parcel3.java // Using .new to create instances of inner classes public class Parcel3 { class Contents { private int i = 11; public int value() { return i; } } class Destination { private String label; Destination(String whereTo) { label = whereTo; } String readLabel() { return label; } } public static void main(String[] args) { Parcel3 p = new Parcel3(); // Must use instance of outer class // to create an instance of the inner class: Parcel3.Contents c = p.new Contents(); Parcel3.Destination d = p.new Destination("Tasmania"); } } ~~~ 在拥有外部类对象之前是不可能创建内部类对象的。这是因为内部类对象会暗暗地连接到建它的外部类对象上。但是,如果你创建的是嵌套类(静态内部类),那么它就不需要对外部类对象的引用。