August 4, 2025
๐ผ Upcasting
- Definition: Casting a subclass object to a superclass type.
- Safe: Always safe, no explicit cast required.
- What is accessible: Only the declared typeโs methods/fields (superclass), unless overridden.
Key Point:
- โ Methods are determined at runtime โ actual object's type (Dog) decides what method is executed (polymorphism).
- โ Attributes/fields (if any) are not polymorphic โ they are resolved at compile-time using the declared type.
๐ฝ Downcasting (Subcasting)
- Definition: Casting a superclass object to a subclass type.
- Risky: Must be done explicitly, and it can throw a ClassCastException if not valid.
- What is accessible: After downcasting, you can access the subclass-specific methods/fields.
Wrong downcast example:
๐ง Summary Table
๐ Real Example with Field
๐ข Mental Model: Think of a Class Hierarchy as a Tree
Object
- The top of the tree is more general (Object, Animal)
- The bottom of the tree is more specific (Dog, Poodle, etc.)
๐ผ Upcasting = Going up the hierarchy
- From specific to general (e.g., Dog โ Animal)
- Safe, because a Dog is always an Animal
- Loses access to specific features
๐ฝ Downcasting = Going down the hierarchy
- From general to specific (e.g., Animal โ Dog)
- Risky, because not all Animals are Dogs
- Gains access to subclass features, but only if valid
๐ง How to Remember
Try one of these mnemonics:
1. "Upcasting climbs the tree, downcasting dives deep."
- Imagine the class hierarchy as a vertical structure (like a tree or org chart).
- "Up" means more general (e.g., to Animal or Object)
- "Down" means more specific (e.g., to Dog)
2. Think in terms of "zoom level":
- Upcasting = zooming out โ you see less detail (fewer features)
- Downcasting = zooming in โ you see more detail (more features, but may not always be safe)
3. Java's automatic vs. manual:
- Upcasting = automatic (Java does it for you)
- Downcasting = manual (you have to tell Java: Dog d = (Dog) a;)
๐งช Example Recap
Upcasting: Dog โ Animal (safe, general)
Downcasting: Animal โ Dog (risky, specific)