Java ProgramsOOPDowncasting

Downcasting in Java

intermediate·  OOP  ·  Inheritance

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.

Input
Employee e = new Manager(); Manager m = (Manager) e;
Output
Manager is managing the team

Java Program

Java
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

Manager is managing the team

Core Logic

Checking instanceof before casting confirms the object genuinely is a Manager, so the explicit cast that follows is guaranteed to succeed.

How It Works
  1. 1Employee e = new Manager(); upcasts a Manager into an Employee-typed reference, same as before.
  2. 2e instanceof Manager checks the object's real runtime type before attempting anything risky.
  3. 3Manager m = (Manager) e; is the downcast itself — the explicit (Manager) cast is required here, unlike upcasting, since the compiler can't otherwise be sure e truly holds a Manager.
  4. 4Once cast, m can call manageTeam(), a method that only exists on Manager.
Since 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).

Key Concepts

downcastingexplicit castinstanceof guard

Related Programs