Cosmic Module
J
Qubits of DPK
March 14, 2026
Core Java
Layman Explanation
Every dog IS an animal. Treating a dog as an animal = upcasting (always safe). Treating an animal as a specific dog = downcasting (only safe if it actually IS a dog).
Upcasting (Implicit / Automatic)
Child reference → Parent reference. Always safe. No cast needed.
java
QUBITS OF DPK
Why upcast?
java
QUBITS OF DPK
Downcasting (Explicit / Manual)
Parent reference → Child reference. Risky. Must cast manually.
java
QUBITS OF DPK
ClassCastException — The Danger
java
QUBITS OF DPK
Safe Downcast with instanceof
java
QUBITS OF DPK
Full Example
java
QUBITS OF DPK
️ Traps
java
QUBITS OF DPK
Interview Answer (SDE-2)
"Upcasting assigns child object to parent reference — automatic, always safe, enables polymorphism. Downcasting converts parent reference back to child to access child-specific methods — must be done explicitly, can throw ClassCastException if actual object type doesn't match. Always use instanceof check before downcasting. Java 16+ pattern matching instanceof combines check and cast in one step. Fields are NOT polymorphic (resolved by reference type), only overridden methods are."
Interview Questions & MAANG-Level Answers
Q1. What is upcasting and downcasting?
Upcasting: assigning a child object to a parent reference — implicit, always safe, no cast needed. Enables polymorphism (write code for Animal, works for Dog/Cat). Animal a = new Dog() — a can only call Animal's methods. Downcasting: casting parent reference back to child type — explicit, risky. Dog d = (Dog) a — safe only if a actually holds a Dog. ClassCastException if actual type doesn't match. Always check with instanceof before downcasting.
Q2. What is ClassCastException? How do you prevent it?
ClassCastException is thrown at runtime when you cast an object to an incompatible type: Animal a = new Cat(); Dog d = (Dog) a — crashes! Prevention:
java
QUBITS OF DPK
In well-designed OOP, frequent downcasting signals a design issue — consider using polymorphism, visitor pattern, or sealed classes instead.
Q3. What is the instanceof operator?
instanceof checks if an object is an instance of a specific type, returning boolean:
java
QUBITS OF DPK
Java 16+ pattern matching combines check and cast: if (a instanceof Dog d) { d.bark(); } — d is automatically cast and scoped to the if block. Used in equals() implementations and type-dispatch logic.
Q4. Are fields polymorphic in Java?
No — fields are resolved by the REFERENCE type at compile time, not the actual object type:
java
QUBITS OF DPK
Only overridden METHODS are polymorphic (resolved at runtime). Fields are HIDDEN, not overridden. This is a classic interview trap.
Q5. What is pattern matching instanceof (Java 16+)?
Pattern matching combines the instanceof check with a variable binding in one expression, eliminating the redundant cast:
java
QUBITS OF DPK