What is Upcasting and Downcasting in Java?

Last updated on Mar 01,2023 68.6K Views

What is Upcasting and Downcasting in Java?

edureka.co

Converting an object from one type to another is a very important aspect of Java which is popularly known as Typecasting. Let’s understand the concepts of Upcasting and Downcasting in Java in the following manner:

 

What are Upcasting and Downcasting in Java?

Upcasting (Generalization or Widening) is casting to a parent type in simple words casting individual type to one common type is called upcasting while downcasting (specialization or narrowing) is casting to a child type or casting common type to individual type.

Upcasting can be done but for downcasting, we need to check the types or else we may get

ClassCastException

 

Hierarchy Example

Let’s take this example.

Food -> Fruit -> Apple, Orange

Food is the interface which is at the topmost level

public interface Food { 
   public float getTotalCalories();
   public String getOrigin();
}

 

The fruit is the abstract class

public abstract class Fruit implements Food {
public float getTotalCalories(){
      return 0.50f;
}
   public String getOrigin();
}

 

Apple and Orange are the two concrete subclasses

public class Apple extends Fruit {
public float getTotalCalories() {
    return 0.40f
}
public String getOrigin() {
    return "someCity";
  }
}
public class Orange extends Fruit {
public float getTotalCalories() {
    return 0.30f
}
public String getOrigin() {
    return "someOtherCity";
}
}

 

In your case, a cast from an Apple to a Fruit is an upcast, because of an Apple is-a Fruit. whenever there is an inheritance i.e is-a relationship between two classes we can do upcasting.

For example, if we cast Apple to Fruit it is upcasting because Apple is of type Fruit here we are generalizing from child type to parent type. So, if there is an is-a relationship (inheritance) between two classes we can upcast.

Let’s look at a downcasting example:

Here we are narrowing the type of object i.e we are converting common type to individual type.

Fruit fruit = new Apple();
Apple castedApple = (Apple) fruit;

 

Here we are casting common type to individual type i.e superclass to subclass which is not possible directly in Java so we explicitly do the casting and tell the compiler that what the runtime type of the object. It is possible in this case because the fruit is Apple even if the reference type is Fruit.

Now, Suppose if you do this:

Fruit fruit = new Fruit();
Apple notApple = (Apple) Fruit;

 

Above code will throw an exception because fruit’s runtime object is Fruit but not Apple it is not possible to cast superclass to subclass so, this will end up with ClassCastException.

If we want to invoke the method of superclass we can simply do this using super keyword as super.methodName() or we can upcast the object.

If we want to invoke subclass’s method then we will need to downcast the object but we can run into ClassCastException so, if you want to avoid this exception you can use a keyword instanceof which will check the runtime type of the object before we cast the object as in below code.

Fruit fruit = getSomeFruit(); #we dont really know what getSomeFruit is returning so we can check the type of fruit using instanceof
if (fruit instanceof Apple) {
    // the object can be casted and the code won't fail
    Apple castedApple = (Apple) fruit;
}

 

As a Java developer, you will come across this usually, you may need to cast objects depending on the requirements so, now you know how to do a casting. And it isn’t really that hard to do.

 

 

Why do we need Upcasting in Java?

Generally, upcasting is not necessary. We need upcasting when we want to write code that deals with only the parent class. Consider the following class

public class CalorieMeter{
     public void readCalorie(Fruit fruit){
          print("Calorie:" + fruit.getTotalCalories());
     }
}

Here we can pass any subtype of Fruit to readCalorie() method, thus it accepts both the objects of Apple and Orange class as they are the subtype of Fruit class.

Apple apple = new Apple();
Orange orange = new Orange();
Caloriemeter caloriemeter = new CalorieMeter();
caloriemeter.readCalorie(apple);
caloriemeter.readCalorie(orange);

 

 

Why do we need Downcasting in Java?

We use downcasting whenever we want to access behaviors of the subtypes. This is used more frequently than that of upcasting. Consider the following example:

public class CalorieMeter{
     public void readCalorie(Fruit fruit){
          print("Calorie:" + fruit.getTotalCalories());
          //if the fruit is orange the object should print city
          if(fruit instanceof Orange){
             Orange orange = (Orange) fruit;
             System.out.println("City:"+fruit.getOrigin());
          }
     }
}

Here in readCalorie() method, we have checked the object which is passed if that object is of type Orange we have to downcast it and invoke the method getOrigin() which will give the origin of that fruit.

 

Important Topics

 

In this article, we covered what is upcasting and downcasting in Java. What is the hierarchy needed so that the object can be upcasted and downcasted also, how to use instanceof operator in order to check the type of object while downcasting so that we can avoid getting ClassCastException. Few import points like while casting only reference of object are changed and while downcasting we should check the type of object and upcasting is safe. If you’re just beginning, then watch at this Java Tutorial to Understand the Fundamental Java Concepts.

Check out the Java Course Online by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this “Java Tutorial” blog  and we will get back to you as soon as possible or you can also join our Java Training in Sharjah.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 1st March,2025

1st March

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES
REGISTER FOR FREE WEBINAR Building Robust Applications with Spring Framework