Downcasting in Java
Problem
Downcasting means converting a reference declared as a parent type back to a subclass type, to reach members the parent type doesn't expose — unlike upcasting, this requires an explicit cast and isn't automatic.
Given an Employee reference that actually holds a Manager, cast it back to Manager to call a Manager-only method.
Java Program
class Employee {
void work() {
System.out.println("Employee is working");
}
}
class Manager extends Employee {
void manageTeam() {
System.out.println("Manager is managing the team");
}
}
public class DowncastingDemo {
public static void main(String[] args) {
Employee e = new Manager(); // upcast first, as usual
if (e instanceof Manager) { // guards the cast below from failing at runtime
Manager m = (Manager) e; // explicit downcast
m.manageTeam();
}
}
}Output
Core Logic
Checking instanceof before casting confirms the object genuinely is a Manager, so the explicit cast that follows is guaranteed to succeed.
- 1
Employee e = new Manager();upcasts a Manager into an Employee-typed reference, same as before. - 2
e instanceof Managerchecks the object's real runtime type before attempting anything risky. - 3
Manager m = (Manager) e;is the downcast itself — the explicit(Manager)cast is required here, unlike upcasting, since the compiler can't otherwise be sureetruly holds a Manager. - 4Once cast,
mcan callmanageTeam(), a method that only exists onManager.
e genuinely refers to a Manager object, the instanceof check passes, the cast succeeds, and m.manageTeam() prints "Manager is managing the team".Key Point: Casting an Employee reference that doesn't actually hold a Manager would throw a ClassCastException at runtime instead of failing at compile time — checking instanceof first, as done here, is what rules that out (exceptions/class-cast-exception.mdx covers that failure case directly).