147

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
  • 19,616
  • 22
  • 63
  • 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

250

You need to prefix the call by the outer class:

Outer.this.show();
Eric
  • 95,302
  • 53
  • 242
  • 374
Guillaume
  • 14,306
  • 3
  • 43
  • 40
  • 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
0

This should do the trick:

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