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

如何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。

谢谢。

回答:

像这样:

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

以上是 从Java内部类访问外部类“ super” 的全部内容, 来源链接: utcz.com/qa/405038.html

回到顶部