Return to site

Upcasting and downcasting in Java

· java

TLDR

  1. Upcasting is safe and implicit, allowing a subclass object to be treated as its superclass. Parent parent = child; // Upcasting
  2. Downcasting is explicit and risky, requiring a cast from a superclass to a subclass, which can throw a ClassCastException if the object is not an instance of the subclass. Child child = (Child) parent; // Downcasting


👆Upcasting

 

is the process of casting a subclass object to a superclass object. It’s always safe and can be done implicitly because a subclass object is always an instance of its superclass. Here’s an example:

 

In this example, child is an instance of Child, which is a subclass of Parent. When we assign child to parent, we’re upcasting the Child object to a Parent reference. The display() method called on parent will execute the overridden method in Child.


👇Downcasting,

 

On the other hand, Downcasting is casting a superclass object into a subclass object. It’s unsafe and must be done explicitly because not all superclass objects are subclass instances. If the cast is incorrect, it will result in a ClassCastException. Here’s an example:

 

In this case, since parent is an instance of Parent, not Child, attempting to cast it to Child will fail at runtime.


To make it work, you should us an upcasting Parent parent = new Child();


🤔BUT, why do we use downcasting if we have to assign an upcasted value?

Downcasting is used when you need to access methods or properties that are specific to a subclass and not available in the superclass. Even though you can assign an upcasted value to a superclass reference, you lose access to the subclass-specific features. Downcasting allows you to retrieve the subclass object and use its unique capabilities.

Here’s a practical example:

 

In this scenario, vehicle is an upcasted Car object. If we want to open the trunk, which is a method only available in Car, we need to downcast vehicle back to Car to access the openTrunk() method.