使用.this和.new
.this
在Java当中,如果你需要生成对外部类对象的引用,那么一种简便的方法是可以使用外部类的名字后面紧跟原点和this。
也就是说有两种方式:
(1) return new DotThis();
(2)return DotThis.this;
public class DotThis {
void f() {
System.out.println("DotThis.f()");
}
public class Inner{
public DotThis outer() {
return DotThis.this;
//return new DotThis();两种不同的方式而已
}
}
public Inner inner() {
return new Inner();
}
public static void main(String[] args) {
DotThis dt= new DotThis();
DotThis.Inner dti=dt.inner();
dti.outer().f();
}
}
.new
有时我们想要告知某些其他对象,去创建其某个内部类的对象。我们必须在new表达式中提供对其他外部类对象的引用。
public class DotNew {
public class Inner{}
public static void main(String[] args) {
DotNew dn = new DotNew();
DotNew.Inner dni = dn.new Inner();
}
}
这告诉我们,