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:

Example

Consider the hierarchy below:

VEHICLE  ===>  4 Wheeler   ===>  Cars   ===>   Alto Maruti

Syntax

alto a=new alto();
    System.out.println(a);
vehicle v=a;                         //upcasting
    System.out.println(v);

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.

Example

class vehicle
{
  void display()
   {
       System.out.println("A");
   }
}
class alto extends vehicle         //class B is inheritng class A 
{
  void display()
   {
       System.out.println("B");
   }
}
class C                            //main class
{
     public static void main(String[] args) 
   {
        alto a=new alto();
        System.out.println("alto");
        vehicle v=a;
        System.out.println("vehicle");
   }
}

Output

alto
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.