這裏的訣竅是知道內部類是如何工作的。它本質上只是一個「普通」的靜態類,但其構造函數隱式獲取對封閉類的引用。所以,這樣的:
public class TopLevel {
public void go() {
new Inner().bar();
}
public void foo() { }
public class Inner {
public void bar() {
TopLevel.this.foo();
}
}
}
是相同的:
public class TopLevel {
public void go() {
new Inner(this).bar(); // explicitly passing in "this"
}
public void foo() { }
public static class Inner {
private final TopLevel parent; // note that we have this new field
public Inner(TopLevel parent) { // note this new constructor
this.parent = parent;
}
public void bar() { // we use the explicit reference instead
parent.foo(); // of the implicit TopLevel.this
}
}
}
因此,與所有的說,重構你的內部類的方式,是一個頂級類是添加一個明確的領域引用UpperClass
實例,並將此引用傳遞給NestedClass
構造函數。換句話說,就像第二個代碼段而不是第一個代碼段。
當你說「upper」時,你的意思是「超級」,還是這是某種你正在寫的Diamond Jubilee慶祝軟件? 8 = \/ – davidfrancis
只需使用AbstractUpperClass.this.someMethod() – Yura
您的代碼無法理解。你能否提供有效的[SSCCE](http://sscce.org/)? –