0
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

1
  • Could you provide an example? Commented Apr 26, 2011 at 10:06

4 Answers 4

5

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 from OuterClass as this is the inner-most enclosing class that defines this method.
Sign up to request clarification or add additional context in comments.

Comments

3

If I've understood correctly what you want, you could do:

OuterClass.this

Comments

2

defined inside a method of an outer class

If its defined inside a method then its scope is limited to that method only.

2 Comments

we can call : new ClassName().Method();
Yes we can. But we can not access variables inside that method.
0

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() {

        }
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.