使用.this
如果你需要声称对外部类对象的引用,可以使外部类的名字后面紧跟圆点和this,这样产生的引用自动的具有正确的类型,这一点在编译期就被知晓并受到检查,因此没有任何运行时开销。下面的例子展示了如何使用this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
public class DotThis {
void f() { System.out.println("DotThis.f()"); } public class Inner{ public DotThis outer() { return DotThis.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(); } }
|
使用.new
有时你可能想告知某些其它对象,去创建其某个内部类的对象。要实现此目的,你必须在new表达式中提供对其他外部类对象的引用,这时需要用new语法,如下:
1 2 3 4 5 6 7
|
public class DotNew { public class Inner{} public static void main(String[] args) { DotNew dn = new DotNew(); DotNew.Inner dni = dn.new Inner(); } }
|
近期评论