142

I have implemented a nested class in Java, and I need to call the outer class method from the inner class.

class Outer {
    void show() {
        System.out.println("outter show");
    }

    class Inner{
        void show() {
            System.out.println("inner show");
        }
    }
}

How can I call the Outer method show?

Santhosh
  • 18,518
  • 21
  • 62
  • 74
  • Can we assume that your inner class holds an instance of the outer class? – Eric May 11 '10 at 06:33
  • 15
    @Eric: in java, an instance of a non-static inner class ALWAYS holds an instance of the outer class – newacct May 11 '10 at 06:35
  • @Eric: that is always true in a non-static Java inner class! – Arne Burmeister May 11 '10 at 06:36
  • Oops. I got mixed up. Can we assume that your _outer_ class holds an instance of the _inner_ class? – Eric May 11 '10 at 06:39
  • @Eric: I think you're even more mixed up now. No, you cannot assume that the outer class holds an instance of the inner class; but that's irrelevant to the question. You're first question (whether the inner class holds an instance of the outer class) *was* the relevant question; but the answer is yes, always. – newacct May 11 '10 at 06:58

2 Answers2

241

You need to prefix the call by the outer class:

Outer.this.show();
Eric
  • 91,378
  • 50
  • 226
  • 356
Guillaume
  • 13,867
  • 3
  • 42
  • 39
  • 3
    Great. I have a follow up on this. How do I call a method in the outer class from a totally different place by having an inner class instance. Inner myInner = new Outer().new Inner(); ... for example if the outer class has a public method getValue(). myInner.getValue() wouldnt work, myInner.Outer.getValue() doesn't either. I know I can do it by having a method getOwner in Inner and then call it.. but do I need that method? thanks – mjs Dec 09 '11 at 13:41
  • If outer is an interface then how to call the abstract method from inner class..? – Kanagavelu Sugumar Aug 08 '17 at 12:49
1

This should do the trick:

Outer.Inner obj = new Outer().new Inner();
obj.show();
eli-k
  • 9,991
  • 11
  • 41
  • 43
vijay surya
  • 137
  • 1
  • 6
  • 1
    He was asking about show() method of Outer class, this call will invoke Inner class's show(). – Ava Feb 19 '20 at 15:41