Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 252
mik01aj Avatar asked Apr 21 '10 20:04

mik01aj


People also ask

Can I access the sub class methods using a super class object?

Yes, you can call the methods of the superclass from static methods of the subclass (using the object of subclass or the object of the superclass).

How do I access private method of superclass?

So, in order to access a private method from outside the class, you need to call one of its public proxies, i.e. one of the public methods of the class which have access to the private method and act as an interface to it, which is what you're doing.

Can you invoke a method in superclass parent class?

We can invoke the overridden method of the parent class with the help of the super keyword. super() is used for executing the constructor of the parent class and should be used in the first line in the derived class constructor.

Can we directly access subclass method from superclass in inheritance?

Does a superclass have access to the members of a subclass? Does a subclass have access to the members of a superclass? No, a superclass has no knowledge of its subclasses.


2 Answers

Bar.super.a() appears to work.

Per JLS section 15.12

ClassName . super . NonWildTypeArguments_opt Identifier ( ArgumentList_opt )

is a valid MethodInvocation

like image 139
ILMTitan Avatar answered Oct 23 '22 18:10

ILMTitan


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

like image 32
Michael Myers Avatar answered Oct 23 '22 17:10

Michael Myers