- 1
Java
what is upcasting and downcasting in Java ? plz explain through code.
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;
}
+ 1
Thank you Magyar David



