Table of Contents
Share this Resource

What is Upcasting and Downcasting in Java Explained

At a Glance

1. Upcasting allows a subclass object to be referenced through a superclass type without an explicit cast.
2. Downcasting allows access to subclass-specific features when the actual object is compatible with the subclass.
3. Upcasting supports polymorphism, making Java applications more flexible and reusable.
4. Invalid downcasting can cause a ClassCastException during execution.
5. The instanceof operator helps verify object compatibility before downcasting.

Can You Predict What Happens?

Animal animal = new Dog();
Dog dog = (Dog) animal;

Question: Does Java create a new Dog object, change the existing object's type or simply allow access through a more specific reference?

Answer: It uses the same object through different reference types!

That's the idea behind upcasting and downcasting in Java. Read on to understand how these conversions work, their differences and when to use them safely.

An Introduction to Upcasting in Java

Upcasting in Java refers to assigning a subclass object reference to a reference variable of its superclass type. It allows developers to treat objects of different subclasses as instances of a common parent class. Upcasting is performed automatically by Java because every subclass object is also an instance of its superclass. Here are some key concepts associated with upcasting in Java:

Concepts of 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, a superclass reference generally allows access to the accessible members defined by its declared type, including inherited members. Subclass-specific members cannot be accessed directly unless the reference is cast to a compatible subclass type.

Java Training

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.

Through upcasting, a superclass reference can invoke an overridden instance method in the subclass. Java selects the appropriate implementation based on the object's actual runtime type, enabling runtime polymorphism.

Common Mistakes to Avoid When Casting in Java

1. Downcasting without checking the object type
2. Assuming casting changes the actual object
3. Accessing subclass-specific members after upcasting
4. Using unnecessary explicit casts
5. Relying too heavily on downcasting

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. After upcasting, accessible members are determined by the reference's declared type. 

Subclass-specific members cannot be accessed directly through that reference, although overridden instance methods can still execute according to the object's runtime type.

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.

For example:

Animal animal = new Dog();
animal.sound();

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. A valid upcast is safe because the subclass is compatible with its superclass type. The widening reference conversion itself does not throw a ClassCastException or require a runtime type check.

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.

Quick Check: Predict the Output

Consider the following code:

Animal animal = new Dog();
animal.sound();
Question: Will Java execute the Animal class's sound() method or the Dog class's overridden method?
Answer: Java executes the Dog class's overridden sound() method because the actual object is an instance of Dog.

Learn the advanced concepts of Java like the Java virtual machine by signing up for the Java Engineer Training now!

Example of Upcasting in Java

Here is an example 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

An Introduction to Downcasting in Java

Downcasting in Java involves converting a reference of a superclass type into a reference of a more specific subclass type. Unlike upcasting, downcasting generally requires an explicit cast. It is used when developers need to access subclass-specific methods or fields that are not available through the superclass reference. However, downcasting is only valid when the actual object is compatible with the target subclass. Here are some key features to know about downcasting in Java:

Concepts of Downcasting in Java

1) Subclass Reference

In downcasting, a reference of a superclass type is cast to a more specific subclass type. This changes how the object is accessed through the reference, not the object's actual runtime type.

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.

For example:

Animal animal = new Dog();
Dog dog = (Dog) animal;

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 pointing to a Dog object, you can downcast it using:

Animal a = new Dog();
Dog d = (Dog) a;

3) Recovering Subclass Features

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

Downcasting allows you to access subclass-specific members through a compatible subclass reference. These members were never removed from the object; they were simply inaccessible through the more general reference type.

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 when a non-null object's runtime type is incompatible with the target type of a checked cast.

To reduce the risk of an invalid cast, you can use the instanceof operator to check whether an object is compatible with the target type before downcasting. Modern Java also supports pattern matching with instanceof, allowing the checked object to be accessed through a pattern variable.

5) Specific Method Invocation

Downcasting in Java allows for specific method invocation of a subclass from a superclass reference. After upcasting, the accessible methods depend on the reference's declared type, including inherited methods. Subclass-specific methods cannot be called directly through the superclass reference.

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.

For example, assuming Dog extends Animal and defines a bark() method:

Animal animal = new Dog();
if (animal instanceof Dog dog) {
    dog.bark();
}

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.

Downcasting should be used when access to subtype-specific behaviour is necessary and the object's runtime type is compatible with the target subclass. Excessive downcasting can increase code complexity and coupling, so polymorphism is often preferable.

Checklist: Before Downcasting an Object in Java

□ Check whether downcasting is necessary.
□ Verify that the object's runtime type is compatible with the target subclass or interface.
□ Use instanceof when the runtime type is uncertain.
□ Confirm that subclass-specific behaviour is actually required.
□ Avoid casting unrelated or incompatible reference types.
□ Consider whether polymorphism offers a cleaner alternative.

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 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:

Difference Between Upcasting and Downcasting in Java

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

The Knowledge Academy
The Knowledge Academy

Global Training Provider

The Knowledge Academy develops accessible learning content across Project Management, IT, Cybersecurity, Data Science, Business Analysis, HR, Accounting and Finance, Leadership and Health and Safety. Its resources combine subject research with clear explanations to help professionals build practical knowledge across a wide range of disciplines.

View Detail icon
cross

BIGGEST HALLOWEEN SALE!

halloween-sale GET UPTO 40% OFF!

* WHO 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.