0
Animal a=new Dog(); Cat c=(Cat)a; System.out.println(c.noise()); Why this causes Run time exception? Cat and Dog are inherited.
Downcasting Upcasting Java
3 Respuestas
+ 1
Hi,
I guess you should be getting ClassCastException;
here you are trying to cast Dog object into Cat which is not possible as Dog & Cat do not inherit each other.
Your current class structure should be as below,
Animal -> Parent
Dog extends Animal
Cat extends Animal
As above, Animal can have an object of both Dog/Cat since both's parent is Animal; But you are trying to creating a object of Dog() and assigned to Animal which holds the dog object and when you try to assign to Cat, it would throw class cast exception since Cat doesn't extend Dog.Hope this was helpful! :)
0
What is SOP supposed to be?
0
system.out.println