如何从嵌套类访问超类方法?

我希望这段代码解释了这个问题:

class Foo { void a() { / *stuff */ } } class Bar extends Foo { void a() { throw new Exception("This is not allowed for Bar"); } class Baz { void blah() { // how to access Foo.a from here? } } } 

我知道我可能做错了,因为inheritance可能不应该以这种方式使用。 但这是我情况下最简单的方法。 而且,除此之外,我只是好奇。 可能吗?

Bar.super.a()似乎有效。

根据JLS第15.12节

class级名称 。 超级 NonWildTypeArguments_opt标识符(ArgumentList_opt)

是一个有效的MethodInvocation

您可以使用Outer.this.method()从外部类调用任何方法。

但是方法在运行时被解析,所以如果你在子类中重写了它,只有子类方法( Bar.a() )可以访问原始方法(通过调用super.a() )。

你可能已经发现,你不能写Bar.this.super.a() – 但即使你可以,它仍会给你Bar.a() ,而不是Foo.a()