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

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.
3

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

OuterClass.this
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
  • we can call : new ClassName().Method(); Apr 26, 2011 at 10:15
  • Yes we can. But we can not access variables inside that method.
    – Harry Joy
    Apr 26, 2011 at 10:18
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() {

        }
    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.