Question

I m Beginner in Java, so someone please say how to call methodA() in Animal Through Mammal object.i cant understand why we need Downcasting and Upcasting clearly.

class Animal{
void methodA(){
    System.out.println("I m Animal");
}
}
class Mammal extends Animal{
    void methodA(){
        System.out.println("I m Mammal child class of Animal");
    }
    void methodAB(){
        System.out.println("Two child class Dog and Cat I have");
    }
}

public class UpDownCast {

public static void main(String[] args) {

Animal a = new Animal();
a.methodA();

Mammal m = new Mammal();
m.methodA();


Animal A = new Mammal();
if (A instanceof Mammal){
    A.methodA();
}
Animal A1= new Animal();
Mammal M1 =(Mammal)A1;
M1.methodA();

}
}

Thanks in Advance.

Was it helpful?

Solution

If your instance is Mammal and if you are calling methodA() (which is overriden in Mammal), java will call Mammal's methodA(). This is called Dynamic Polymorphism

To call methodA() of Animal from Mammal class, you need to invoke it using super keyword, within the Mammal class, something like below

class Mammal extends Animal{
    void methodA(){
        super.methodA();// --> calling Animal's methodA()
    }
    void methodAB(){
        System.out.println("Two child class Dog and Cat I have");
    }
}

Also, below statement will cause ClassCastException as Animal IS NOT A Mammal (where as a Mammal IS A Animal )

Animal A1= new Animal();
Mammal M1 =(Mammal)A1;
M1.methodA();

OTHER TIPS

how to call methodA() in Animal Through Mammal object.

For that you have to ovveride the methodA in Mammal and if you have a Mammal object with you,you can directly call it.In that case no need of casting.

First, you must understand, that by casting you are not actually changing the object itself, you are just labeling it differently.

enter image description here

You cannot call the method of superclass through the subclass object if you have overriden the method. As in your case Mammal is the subclass of Animal, hence when you use Mammal object, JVM will look for the methodA implmentation in the Mammal class first, if exists then it will call the Mammal class method, otherwise Animal class method will be called.

The idea is quite logical in terms of inheritence, if child has a behavior inherited from Parent and someone calls that behavior on child, then child method will execute. If child does not have a behavior of its own then it will simply inherit it from Parent and hence Parent's method will be called.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top