从Java中的内部类访问外部类“super”

时间:2011-10-24 11:23:49

标签: java inner-classes

如何从内部类访问外部类super

我重写了一个让它在不同的线程上运行的方法。从内联线程,我需要调用原始方法,但当然只是调用method()将变成无限递归。

具体来说,我正在扩展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();
          [..]
    }
}

这个地方给了我一个我无法找到的NullPointerException。

感谢。

1 个答案:

答案 0 :(得分:76)

像这样:

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();
    }
}

上述测试在执行时显示:

Blah
Outer@1e5e2c3