[英]How to call an instance of a class defined inside a method of an outer class
class Outer{
public void Method(){
int i=10;
System.out.println(i);
Class InsideMethod{
//
}
}
問題:如何在方法外部調用InsideMethod對象
此片段說明了各種可能性:
public class Outer {
void onlyOuter() { System.out.println("111"); }
void common() { System.out.println("222"); }
public class Inner {
void common() { System.out.println("333"); }
void onlyInner() {
System.out.println("444");// Output: "444"
common(); // Output: "333"
Outer.this.common(); // Output: "222"
onlyOuter(); // Output: "111"
}
}
}
注意:
common();
調用從內部類調度實現。 OuterClass.this
構造來指定您要從外部類分派一個方法(繞過隱藏) onlyOuter()
調度從所述方法OuterClass
,因為這是最內封閉類定義此方法。 如果我已正確理解您的要求,則可以執行以下操作:
OuterClass.this
在外部類的方法內部定義
如果在方法內部定義了它,則其范圍僅限於該方法。
根據我對您的問題的理解...(請參見下面的示例), 不能從方法'doOuter'外部引用在外部類的方法中定義的類'Elusive'的實例。
public class Outer {
public void doOuter() {
class Elusive{
}
// you can't get a reference to 'e' from anywhere other than this method
Elusive e = new Elusive();
}
public class Inner {
public void doInner() {
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.