Search code examples
javaextend

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);

Solution

  • 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);
    }