How to access superclass method from nested class?

I hope this code explains the problem:

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? } } } 

I know that I can do something wrong, because inheritance may not be used that way. But this is the easiest way in my situation. And besides, I'm just curious. Is it possible?

+7
java inheritance
source share
2 answers

Bar.super.a() seems to work.

Per JLS section 15.12

ClassName super. NonWildTypeArguments_opt ID (ArgumentList_opt)

- valid Invocation method

+16
source share

You can call any method from an external class using Outer.this.method() .

But methods are allowed at runtime, so if you redefined it in your subclass, only the subclass method ( Bar.a() ) can access the original (by calling super.a() ).

As you probably discovered, you cannot write Bar.this.super.a() - but even if you could, it would still give you Bar.a() , not Foo.a() .

+3
source share

All Articles