简体   繁体   中英

How to access a superclass method from a 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 may be doing something wrong, because inheritance perhaps shouldn't be used in such way. But it's the easiest way in my situation. And, beside that, I'm just curious. Is it possible?

Bar.super.a() appears to work.

Per JLS section 15.12

ClassName . super . NonWildTypeArguments_opt Identifier ( ArgumentList_opt )

is a valid MethodInvocation

You can call any method from the outer class with Outer.this.method() .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM