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

25th Dec 2016, 12:47 PM
Aayush Agarwal
3 odpowiedzi
+ 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! :)
25th Dec 2016, 3:54 PM
Yukeshkumar N
Yukeshkumar N - avatar
0
What is SOP supposed to be?
25th Dec 2016, 2:00 PM
Eva
Eva - avatar
0
system.out.println
25th Dec 2016, 2:02 PM
Aayush Agarwal