[英]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{
//
}
}
Question : How can I call InsideMethod object outside of the method 问题:如何在方法外部调用InsideMethod对象
This snippet illustrates the various possibilities: 此片段说明了各种可能性:
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"
}
}
}
Note: 注意:
common();
因此, common();
call dispatches the implementation from the inner class. 调用从内部类调度实现。 OuterClass.this
construct for specifying that you want to dispatch a method from the outer class (to bypass the hiding) 使用OuterClass.this
构造来指定您要从外部类分派一个方法(绕过隐藏) onlyOuter()
dispatches the method from OuterClass
as this is the inner-most enclosing class that defines this method. 呼叫onlyOuter()
调度从所述方法OuterClass
,因为这是最内封闭类定义此方法。 如果我已正确理解您的要求,则可以执行以下操作:
OuterClass.this
defined inside a method of an outer class 在外部类的方法内部定义
If its defined inside a method then its scope is limited to that method only. 如果在方法内部定义了它,则其范围仅限于该方法。
From what I've understood of your question... (see the example below), the instance of class 'Elusive' defined within a method of an outer class cannot be referenced from outside of method 'doOuter'. 根据我对您的问题的理解...(请参见下面的示例), 不能从方法'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.