What is Upcasting and Downcasting in Java

Upcasting means an object of subclass type can be treated as an object of the superclass type. Casting here doesn’t mean changing one primitive to another. Upcasting is done automatically while Downcasting needs to be done manually at the time of programming. On the other hand, Downcasting means converting a superclass type to a subclass type.

Now, let’s understand this topic with the help of an example:


Consider the hierarchy below:
VEHICLE  ===>  4 Wheeler   ===>  Cars   ===>   Alto Maruti


Different Syntax for upcasting are

  • vehicle v = (vehicle) new alto();
  • vehicle v = new alto();

Alto is also car and 4 wheeler vehicle, which logically means – if a car has steering and 4 wheeler vehicle has seats, then alto has a steering and seats too.
What this means for a programmer, is that we don’t need to write for every possible 4 wheeler vehicle that it has staring or seats. We just need to write it once, and every car gets it through inheritance.
Alto is still alto but compiler treat it as a vehicle.



First, one must understand that by casting, you are not actually changing the object itself but just labeling it differently. One question arises in my mind that why upcasting is done automatically and downcasting is done manually?
So the simple answer to the above question is that upcasting can never fail and in the case of downcasting there are chances of failure.

Leave a Reply

Contact Us
close slider
Contact Us

How can we help you with?