Samarth2011
Samarth2011

Reputation: 1343

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

Upvotes: 0

Views: 370

Answers (4)

Itay Maman
Itay Maman

Reputation: 30733

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.

Upvotes: 5

Ryan Fernandes
Ryan Fernandes

Reputation: 8536

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

        }
    }

}

Upvotes: 0

Harry Joy
Harry Joy

Reputation: 59694

defined inside a method of an outer class

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

Upvotes: 2

Alberto Zaccagni
Alberto Zaccagni

Reputation: 31590

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

OuterClass.this

Upvotes: 3

Related Questions