- 1

Java

what is upcasting and downcasting in Java ? plz explain through code.

28th Nov 2016, 4:38 PM
Khomendra kumar
Khomendra kumar - avatar
2 Answers
+ 1
Example classes: class Animal { ... } class Fox extends Animal { ... } class Cat extends Animal { ... } UPCASTING: Fox fox = new Fox(); Animal animal = fox; //We know Fox is Animal, so upcasting is "riskless", any Fox or Cat object can be placed into Animal variable, so can be upcasted. DOWNCASTING: Animal animal = new Fox(); Fox fox = (Fox) animal; //Not all Animal is Fox, so it is "risky" to say, it is. If not, than ClassCastException is thrown: Animal animal = new Cat(); Fox fox = (Fox) animal; --> does throw ClassCastException //That's why it is usually encapsuled into a check if: if (animal instanceof Fox) { Fox fox = (Fox) animal; //or directly: ((Fox)animal).doFoxThing; }
28th Nov 2016, 5:55 PM
Magyar DĂĄvid
Magyar DĂĄvid - avatar
+ 1
Thank you Magyar David
29th Nov 2016, 6:14 AM
Khomendra kumar
Khomendra kumar - avatar