agarwal_achhnera
agarwal_achhnera

Reputation: 2456

how to access overridden, non static method of abstract class in subclass

In my program there are only two classes one is Parent ,which is an abstract class and having a non static concrete method, void show(), now there is another class, Child which extends the abstract class, Parent and override the show() method. So now is there any way to access the method of abstract class from main method of Child class with out calling another non static method of Child class.

Upvotes: 1

Views: 3917

Answers (4)

Viruzzo
Viruzzo

Reputation: 3025

Since Child.show() is static, you must do this:

class Child extends Parent {
    static void show() {
        Child c = new Child();
        c.myShow();
    }

    void show() {
         super.show();
    }
}

Answer to the edited post: you cannot call a non-static method without an instance. Every other detail of this situation is irrelevant if you can't/don't want to create an instance of either Parent or Child, as it is just no possible. The question now becomes: Why would you want to do that? What are trying to achieve?

Upvotes: 3

Alnitak
Alnitak

Reputation: 339816

This is what you're looking for:

super.show();

although that'll only work from within a (non-static) member function of the subclass.

There's no direct way to call an overridden method from another class. Your only option would be to have the subclass expose a new method that does nothing but call the parent's overridden method.

However if you do need to do that it suggests that your class hierarchy is incorrectly designed...

Upvotes: 1

DejanLekic
DejanLekic

Reputation: 19787

A child class can always use the super keyword to access a method of its superclass. So, in Child class, you may do super.show();.

Upvotes: 0

Roger Lindsjö
Roger Lindsjö

Reputation: 11543

To access parent methods you prefix the call with "super". So, in your case use:

super.show();

Upvotes: 1

Related Questions