class Outer{
public void Method(){
int i=10;
System.out.println(i);
Class InsideMethod{
//
开发者_Python百科 }
}
Question : How can I call InsideMethod object outside of the method
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:
- A method of inner class hides a similarly named method of the outer class. Hence, the
common();
call dispatches the implementation from the inner class. - The use of the
OuterClass.this
construct for specifying that you want to dispatch a method from the outer class (to bypass the hiding) - The call
onlyOuter()
dispatches the method fromOuterClass
as this is the inner-most enclosing class that defines this method.
If I've understood correctly what you want, you could do:
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'.
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() {
}
}
}
精彩评论