How to access a superclass method from a nested class?

后端 未结 2 1566
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-12 04:48

I hope this code explains the problem:

class Foo {
    void a() { / *stuff */ }
}

class Bar extends Foo {
    void a() { throw new Exception(\"This is not a         


        
相关标签:
2条回答
  • 2021-01-12 05:19

    Bar.super.a() appears to work.

    Per JLS section 15.12

    ClassName . super . NonWildTypeArguments_opt Identifier ( ArgumentList_opt )

    is a valid MethodInvocation

    0 讨论(0)
  • 2021-01-12 05:23

    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().

    0 讨论(0)
提交回复
热议问题