John Smith
John Smith

Reputation: 874

Inheritance can't call child class method

Hey i'm trying to call child class method(ChildClass extends SuperClass())

SuperClass s=new ChildClass();
s.childClassMethod();

It doesn't see the ChildClass method the only methods i can call are from SuperClass() i know it's propably a stupid question but anyway cheers

Upvotes: 3

Views: 5259

Answers (4)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48743

The parent does not know anything about any new methods the child possesses.

public class SuperClass {
    // I have no method named "childClassMethod"...
}

public class ChildClass {
    public void childClassMethod() {
        // Do something.
    }
}

SuperClass does not know about childClassMethod(). You would have to provide both classes with an interface or add that method to the parent and override it in the child.

Or, you could simply cast the object to the child class as others have suggested, but this can be unsafe.

((ChildClass) s).childClassMethod()

Upvotes: 3

Petr Mensik
Petr Mensik

Reputation: 27536

That's right, you can't see it because s is type SuperClass which doesn't have this method - this would obviously break Polymorphism principle.

So you either have to change the code like ((ChildClass) s).childClassMethod(); or make s as ChildClass type.

Upvotes: 6

Gabs00
Gabs00

Reputation: 1877

That is because the super class does not have that method.

If you want the super class to be able to call the method, you need to make it abstract and give it that method.

The subclass is a form of the super class, the super class is not a form of the sub class.

Upvotes: 2

Jigar Joshi
Jigar Joshi

Reputation: 240996

Compiler doesn't know what instance this reference would be pointing to at runtime so it will only allow you to access super class's accessible methods at compile time

See

Upvotes: 3

Related Questions