Training Outcomes Within Your Budget!

We ensure quality, budget-alignment, and timely delivery by our expert instructors.

Share this Resource

Table of Contents

What is Upcasting and Downcasting in Java

Upcasting and Downcasting are fundamental concepts in Java that play a crucial role in handling class hierarchies and object references. Upcasting involves converting a subclass object to a superclass reference, promoting code flexibility and supporting polymorphism. On the other hand, downcasting allows the recovery of subclass-specific features by converting a superclass reference back to a subclass type. 

According to the State of Developer Ecosystem report of 2022, about 48 per cent of developers used Java in the year 2021. The same report reveals how Java has been valued consistently among developers from 2017 to 2022. These statistics demonstrate the consistent demand for   Java among developers over the years.  

Now let us explore the two abovementioned concepts in Java in further detail. Upcasting and downcasting in Java allow you to work with objects of different types in a polymorphic manner, leveraging the legacy relationships between classes. 

Table of Contents 

1) A brief introduction to Typecasting in Java 

2) An introduction to What is Upcasting in Java 

      a) Example of Upcasting in Java 

3) An introduction to What is Downcasting in Java 

      a) Example of Upcasting in Java 

4) Key distinctions between Upcasting and Downcasting in Java 

5) Conclusion 

Introducing the concept of typecasting in Java 

Typecasting is an essential concept that allows one data type to be converted into another. It's a way for programmers to utilise and manage various data types more effectively. There are two types of typecasting in Java, namely primitive typecasting and reference typecasting.  

Now primitive typecasting involves fundamental data types such as int, char, float, and others, while reference typecasting concerns object references, often involving classes and their hierarchies. 

Furthermore, in reference to typecasting, you encounter two further classifications namely Upcasting and Downcasting. These terminologies are used when superclass and subclass relationships exist. They represent the conversion from subclass to superclass (upcasting) and superclass to subclass (downcasting), respectively. Here are the two types briefly explained as follows: 

1) Upcasting: Referred to as "widening", Upcasting is the process of converting a subclass reference into a superclass reference. It's absolutely safe and performed automatically by Java because a subclass is an instance of its superclass. For example, if 'Dog' is a subclass of 'Animal', any dog is fundamentally an animal, making upcasting a logical operation. 

2) Downcasting: Downcasting is a process that involves transforming a superclass reference into a subclass reference. Contrary to upcasting, downcasting, often called "narrowing", is not performed automatically and is potentially unsafe. It can lead to a ClassCastException if the object being downcasted is not actually an instance of the subclass.

Java Training
 

An introduction to Upcasting in Java 

Upcasting in Java basically refers to the process where a subclass is converted into a superclass reference. Here are the various points highlighting the concept of Upcasting in further detail below:

What is Upcasting in Java

1. Superclass reference 

A superclass reference refers to the ability to use a reference variable of a superclass to point to an instance (object) of its subclass. This is the core concept behind upcasting. Through upcasting, an object of a subclass type may be assigned to a reference variable of a superclass type. However, while using a superclass reference, you can only access the methods and fields declared in the superclass and not those specific to the subclass. 

2. Automatic conversion 

Automatic conversion, or implicit typecasting, is a key characteristic of upcasting in Java. During upcasting, a subclass reference is automatically converted to a superclass reference without needing any explicit typecasting syntax.  

Additionally, the Java compiler manages this behind the scenes, eliminating the need for developers to manually perform the cast. This ensures ease and efficiency, providing a seamless mechanism for handling the complexities of class hierarchies and promoting code scalability and flexibility. 

3. Polymorphism support 

Upcasting in Java plays a pivotal role in supporting polymorphism, a cornerstone of object-oriented programming. Polymorphism allows objects of many types to be treated as objects of a common supertype.  

Now by Upcasting, you can use a superclass reference to invoke overridden methods in the subclass, thus achieving runtime polymorphism. This mechanism helps in creating more generic, flexible, and reusable code, as you can write methods that work on the superclass and let those methods interact with any subclass objects. 

4. Accessibility limitations 

In Upcasting, while a subclass object can be treated as an object of its superclass, there are certain limitations on what can be accessed. Once an object is upcasted, only the methods and fields of the superclass remain accessible.  

Furthermore, subclass-specific members are no longer reachable through the superclass reference. Despite the fact that the original object is of the subclass type, this restriction arises because the reference used after Upcasting is of the superclass type. 

5. Enhanced flexibility 

Upcasting enhances the flexibility and scalability of Java code. By allowing a subclass object to be treated as its superclass, you can create methods that work with the general superclass type, yet these methods can interact with any subclass object. This reduces redundancy and makes the code more adaptable to changes. For example, if multiple subclasses share a common behaviour in the superclass, you can utilise the superclass reference to call that behaviour, making the code more general.

6. Safe operation

Upcasting in Java is deemed a safe operation because it involves converting a subclass reference into a superclass reference. As a subclass is inherently an instance of its superclass, this conversion is logically sound and doesn't lead to any runtime exceptions or errors.  

Moreover, there is no risk of encountering a ClassCastException during upcasting, unlike with Downcasting. This safety feature simplifies the use of Upcasting and allows it to be performed automatically by the Java compiler. 

Learn the advanced concepts of Java like the Java Virtual Machine by signing up for the Java Engineer Training Course now! 

Example of Upcasting in Java 

Here is an example code which demonstrates Upcasting in Java:
 

class Animal { 

  void sound() { 

    System.out.println("Animal makes a sound"); 

  } 

} 

class Dog extends Animal { 

  void sound() { 

    System.out.println("Dog barks"); 

  } 

} 

class Cat extends Animal { 

  void sound() { 

    System.out.println("Cat meows"); 

  } 

} 

public class TestUpcasting { 

  public static void main(String[] args) { 

    Animal a; // Reference of superclass 

    a = new Dog(); // Upcasting (Dog is automatically upcasted to Animal) 

    a.sound(); // Calls the Dog class method 

    a = new Cat(); // Upcasting (Cat is automatically upcasted to Animal) 

    a.sound(); // Calls the Cat class method 

  } 

} 

Output of the code above

Dog barks 

Cat meows

 

Create your websites and applications with Java, by signing up for the Java Programming Course now! 

An introduction to Downcasting in Java 

Downcasting refers to a process that involves transforming a superclass reference into a subclass reference. Here are the various points highlighting the concept of Downcasting below:

Concepts of Downcasting in Java

1. Subclass reference 

In Downcasting, a subclass reference comes into play when a superclass object is converted to a subclass type. This involves changing the object's type from a more general one (superclass) to a more specific one (subclass).  

Furthermore, the process allows a superclass to be treated as one of its subclasses. Using a subclass reference after Downcasting, you can access both the superclass and subclass members, regaining access to subclass-specific methods or fields that were inaccessible due to upcasting. 

2. Explicit conversion 

Explicit conversion in Downcasting refers to the necessity for developers to manually perform the casting. Unlike upcasting, which is implicitly done by the Java compiler, downcasting requires a specific cast operator. This involves using parentheses syntax (SubclassName) to cast the superclass reference back to the subclass.  

For example, if ‘a’ is an Animal reference and ‘d’ is a ‘Dog’ subclass, you would do the downcasting as ‘d = (Dog) a’. It's important to perform this correctly to avoid runtime exceptions. 

3. Recovering subclass features 

In Java, one key benefit of Downcasting is the recovery of subclass features. Once an object is upcasted, the subclass-specific methods or fields become inaccessible through the superclass reference.  

However, by Downcasting, you can regain access to these subclass-specific members. This means if you have a method or field that exists only in the subclass and not in the superclass, you can access it once again after Downcasting, thus leveraging the more specific functionalities of the subclass. 

4. Runtime risk 

Downcasting in Java comes with certain risks. It's not always guaranteed to be safe and can potentially result in a ‘ClassCastException’ at runtime. This happens if the object being downcasted doesn't actually belong to the subclass.  

Now to avoid this, you should typically use the ‘instanceof’ keyword to verify the type of the object before performing the downcast. Without this check, your code may compile fine but throw an exception during execution, highlighting the inherent runtime risk of downcasting. 

5. Specific method invocation 

Downcasting in Java allows for specific method invocation of a subclass from a superclass reference. After an object has been upcasted, it can only access methods declared in the superclass.  

However, with Downcasting, you regain the ability to call methods that are specific to the subclass. This means that you can use a superclass reference to call a method that only exists in the subclass. This flexibility can be crucial in cases where subclass-specific behaviour is needed. 

6. Limited use cases 

While Downcasting in Java is a powerful feature, it has limited use cases and should be applied judiciously. Its main purpose is to access subclass-specific methods or fields that are not accessible through a superclass reference.  

However, excessive use of downcasting can make the code complex, harder to read and maintain. Thus, it's generally used sparingly and in scenarios where upcasting has previously occurred or when it's necessary to use more specific features of the subclass object. 

Get to know more about how to build dynamic web applications by signing up for Web Development Using Java Training now! 

Example of Downcasting in Java 

Here is an example code which demonstrates Downcasting in Java: 
 

class Animal { 

  void sound() { 

    System.out.println("Animal makes a sound"); 

  } 

} 

class Dog extends Animal { 

  void bark() { 

    System.out.println("Dog barks"); 

  } 

} 

public class TestDowncasting { 

  public static void main(String[] args) { 

    Animal a = new Dog(); // Upcasting 

    Dog d = (Dog) a; // Downcasting 

    d.sound(); // Calls the Animal class method 

    d.bark(); // Calls the Dog class method 

  } 

} 

Output of the code

Animal makes a sound 

Dog barks 

 

Key distinctions between Upcasting and Downcasting in Java 

Here are the key distinctions between Upcasting and Downcasting in Java, listed in the table below:
 

Aspect 

Upcasting 

Downcasting 

Definition 

Upcasting is the process of converting a subclass reference to a superclass reference. It's also known as "Widening." 

Downcasting is the conversion of a superclass reference to a subclass reference. This is also termed as "Narrowing." 

Automatic or explicit 

Upcasting is performed automatically by the Java compiler. There's no need to explicitly cast the object. 

Downcasting is not automatic. It requires explicit casting using parentheses syntax (SubclassName). 

Accessibility 

After upcasting, only the members of the superclass are accessible.  

You cannot access the methods or fields that are specific to the subclass. 

After downcasting, you can access both the superclass and subclass members.  

The access gives access to the subclass-specific methods or fields. 

Safety 

Upcasting is safe as a subclass is an instance of its superclass. There is no risk of ClassCastException. 

Downcasting is potentially unsafe. If the object being downcasted is not actually an instance of the subclass, it can throw a ClassCastException.

Usefulness 

Upcasting is useful to achieve polymorphism where a subclass can be treated as its superclass and the common behaviour can be called. 

Downcasting is used when it is necessary to access subclass-specific behaviour that is not accessible through the superclass reference

Flexibility 

 

Upcasting enhances code flexibility and scalability by allowing the treatment of subclass objects as superclass objects.  

This is beneficial when many subclasses share a common behaviour defined in the superclass. 

Upcasting enhances code flexibility and scalability by allowing the treatment of subclass objects as superclass objects.  

This is beneficial when many subclasses share a common behaviour defined in the superclass. 

 

Conclusion 

Upcasting and Downcasting in Java are essential techniques that enable developers to handle class hierarchies with flexibility and precision. Upcasting provides safe and automatic conversion of subclass objects to superclass references. On the other hand, Downcasting allows for the recovery of subclass-specific features. These programming mechanisms help developers leverage their creation of efficient, reusable and dynamic object-oriented solutions. 

Learn to write, compile and debug Java programs by signing up for Java Training Courses now! 

Frequently Asked Questions

Upcoming Programming & DevOps Resources Batches & Dates

Date

building Java Programming

Get A Quote

WHO WILL BE FUNDING THE COURSE?

cross

OUR BIGGEST SPRING SALE!

Special Discounts

red-starWHO WILL BE FUNDING THE COURSE?

close

close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.

close

close

Press esc to close

close close

Back to course information

Thank you for your enquiry!

One of our training experts will be in touch shortly to go overy your training requirements.

close close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.