Careeroza
Upcasting and Downcasting
Casting Between Parent and Child
| Upcasting | Downcasting | |
|---|---|---|
| Direction | child → parent | parent → child |
| Syntax | Animal a = new Dog(); (automatic) | Dog d = (Dog) a; (explicit) |
| Safe? | always | only if the object really is a Dog |
| Can call | only parent methods | child methods too |
Safe Downcasting with instanceof
Example
Check with instanceof before casting. Java 16+ lets you bind a variable in the check itself (a instanceof Dog d).
public class Main {
public static void main(String[] args) {
Animal[] animals = { new Dog(), new Cat(), new Dog() };
for (Animal a : animals) {
a.eat();
if (a instanceof Dog d) { // check + cast in one step
d.fetch();
}
}
}
}
class Animal {
void eat() { System.out.println(getClass().getSimpleName() + " eats"); }
}
class Dog extends Animal {
void fetch() { System.out.println(" Dog fetches the ball"); }
}
class Cat extends Animal { }Output
Dog eats Dog fetches the ball Cat eats Dog eats Dog fetches the ball
ClassCastException
Example
Casting to the wrong type compiles but fails at runtime.
public class Main {
public static void main(String[] args) {
Object o = "I am a String";
System.out.println("Length: " + ((String) o).length());
Integer n = (Integer) o; // wrong type
System.out.println(n);
}
}Output
Length: 13 Exception: java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap')