Return to site

[VV121] The Java 21 Newsletter: ๐Ÿ”ผ Upcasting and ๐Ÿ”ฝ Downcasting (Subcasting)

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)