Back to course

Polymorphism 2: Understanding Casting in Polymorphism

Java Mastery: From Zero to Professional Developer (50-Lesson Journey)

Lesson 23: Polymorphism 2: Understanding Casting

When using polymorphic references, Java restricts access to only the methods defined in the reference type (the parent class). To access methods specific to the actual child object, we must use casting.

1. Upcasting (Implicit)

Assigning a subclass object to a superclass reference variable is called upcasting. This is safe and automatic because the subclass is guaranteed to have all members of the superclass.

java class Manager extends Employee { /* ... */ }

Employee emp = new Manager(); // Upcasting happens implicitly

2. Downcasting (Explicit)

Assigning a superclass reference to a subclass reference variable requires explicit casting. This is potentially unsafe, as you might try to cast a generic parent object into a specific child type it isn't.

java Employee emp2 = new Manager();

// Downcasting: We explicitly tell the compiler we know it's a Manager. Manager mgr = (Manager) emp2; // Now 'mgr' can access Manager-specific methods

// Cautionary Example: Employee emp3 = new Employee(); // Manager badMgr = (Manager) emp3; // RUNTIME ERROR! ClassCastException

3. Checking Object Type (instanceof)

Before downcasting, you should always verify the actual object type using the instanceof operator to prevent a ClassCastException.

java Vehicle v = new Truck(); // v is actually a Truck

if (v instanceof Truck) { System.out.println("The object is a Truck, safe to downcast."); Truck t = (Truck) v; t.loadCargo(); // Accesses Truck-specific method } else { System.out.println("The object is not a Truck."); }

Modern Java Note (JDK 16+): Java introduced pattern matching for instanceof, which simplifies the downcasting step:

java if (v instanceof Truck t) { // 't' is automatically casted if true t.loadCargo(); }