Access outer class "super" from inner class in Java

pistacchio picture pistacchio · Oct 24, 2011 · Viewed 22.4k times · Source

How can I access outer class' super from an inner class?

I'm overriding a method to make it run on a different thread. From an inline Thread, I need to call the original method but of course just calling method() would turn into an infinite recursion.

Specifically, I'm extending BufferedReader:

public WaitingBufferedReader(InputStreamReader in, long waitingTime)
{
    [..]
    @Override
    public String readLine()
    {
        Thread t= new Thread(){
            public void run()
            {
                try { setMessage(WaitingBufferedReader.super.readLine()); } catch (IOException ex) { }
            }
         };

          t.start();
          [..]
    }
}

This somewhere gives me a NullPointerException I'm not able to find.

Thanks.

Answer

Lukas Eder picture Lukas Eder · Oct 24, 2011

Like this:

class Outer {
    class Inner {
        void myMethod() {
            // This will print "Blah", from the Outer class' toString() method
            System.out.println(Outer.this.toString());

            // This will call Object.toString() on the Outer class' instance
            // That's probably what you need
            System.out.println(Outer.super.toString());
        }
    }

    @Override
    public String toString() {
        return "Blah";
    }

    public static void main(String[] args) {
        new Outer().new Inner().myMethod();
    }
}

The above test, when executed, displays:

Blah
Outer@1e5e2c3