PugsOverDrugs
PugsOverDrugs

Reputation: 535

Class Extension Java

I have class A, and class B ( extends A ). I'm attempting to call out methods from class B, when B is cast as A. Is this possible?

Ex.

A myObject = new B();
myObject.myMethodFoundInB(param);

Upvotes: 0

Views: 135

Answers (3)

JJ.
JJ.

Reputation: 5475

You can do it by casting back to B, ie:

A myObject = new B();
((B)myObject).myMethodFoundInB(param);

or, more safely:

A myObject = new B();
if (myObject instanceof B) {
    ((B)myObject).myMethodFoundInB(param);
}

Upvotes: 3

jordan
jordan

Reputation: 1017

This is only possible if "myMethodFoundInB" is declared in class A, which I'm guessing it isnt.

Upvotes: -1

Juned Ahsan
Juned Ahsan

Reputation: 68715

If the method is not defined in parent then you wouldn't be able to call it using the parent class reference.

You may just define an abstract method myMethodFoundInB in your parent class and override in your child class. Then you will be able to call myMethodFoundInB using parent class reference as well.

Upvotes: 0

Related Questions