Upcasting Vs Downcasting in Java

What are Upcasting and Downcasting in Java?

In Java, we have two ways of object typecasting: Upcasting and Downcasting.

  • Upcasting – Java permits an object of a subclass type to be treated as an object of any superclass type. We can access a method or field from the parent class via a child object.
    Upcasting is done automatically.
  • Downcasting – When we want a Parent class reference to access a method or field declared in a child class, we must explicitly cast the parent object to the child object.

Upcasting 

When performing upcasting, we assign an object of a sub-class to a reference of superclass type.

Using this reference, we can access objects and fields within a subclass, but only those inherited from the superclass.

Example:

class Vehicle {
    
  int maxSpeed = 250;
    
  public void printMaxSpeed() {
    System.out.println("Max speed: " + maxSpeed);
  }
}

class Car extends Vehicle {
    
  int maxSpeed = 300;
    
  @Override
  public void printMaxSpeed() {
    System.out.println("Max speed: " + maxSpeed);
  }
}

class Test {
    
  public static void main(String[] args) {
    Vehicle vehicle = new Car();  // upcasting - casting child class to parent class
    vehicle.printMaxSpeed();
  }
}
Output: Max speed: 300
 

In the above example, we inherit and override the printMaxSpeed ​​method in the Car class, and then in the main method, we assign a Car object to a reference of Vehicle type.
Using the vehicle variable we called the method from the subclass (Car), which is declared in the parent class (Vehicle).

Downcasting

When we want to call a method declared in a sub-class via a reference of the superclass type, we have to perform explicit casting or downcasting.

Example:

class Vehicle {
    
  int maxSpeed = 250;
    
  public void printMaxSpeed() {
    System.out.println("Max speed: " + maxSpeed);
  }
}

class Car extends Vehicle {
    
  int maxSpeed = 300;
  String colour = "Blue";
  
  @Override
  public void printMaxSpeed() {
    System.out.println("Max speed: " + maxSpeed);
  }
    
  public void printColour() { // This method is declared in a sub-class and it's not visible from the superclass.
    System.out.println("Colour: " + colour);
  }
}

class Test {
    
  public static void main(String[] args) {
    Vehicle vehicle = new Car();
    
   ((Car) vehicle).printColour(); // downcasting - calling method declared in the subclass using reference of superclass type
  
  }
}
Output: Colour: Blue
 

In the example above, you can see how we had to explicitly cast a call to a method from the Car class using a variable of type Vehicle.

We had to perform downcasting because we could not reference the method printColour using a variable vehicle. After all, it is invisible to the superclass.

That was all about Upcasting and Downcasting in Java!

 

Leave a Reply

Your email address will not be published. Required fields are marked *