0
0
Javaprogramming~7 mins

Upcasting and downcasting in Java

Choose your learning style9 modes available
Introduction

Upcasting and downcasting help you use objects in flexible ways by changing how you see them in your code.

When you want to treat a specific object as a more general type to use common features.
When you need to access special features of a specific object after treating it generally.
When working with collections that hold general types but contain specific objects.
When overriding methods and you want to call the right version based on the object type.
Syntax
Java
Upcasting:
SuperClass obj = new SubClass();

Downcasting:
SubClass obj = (SubClass) superObj;

Upcasting is automatic and safe because a subclass is always a type of superclass.

Downcasting needs a cast and can cause errors if the object is not actually the subclass.

Examples
Here, Dog is a subclass of Animal. We first upcast Dog to Animal, then downcast back to Dog.
Java
Animal animal = new Dog();  // Upcasting
Dog dog = (Dog) animal;       // Downcasting
Car is a type of Vehicle. Upcasting lets us use Car as a Vehicle. Downcasting recovers the Car features.
Java
Vehicle vehicle = new Car();  // Upcasting
Car car = (Car) vehicle;       // Downcasting
Sample Program

This program shows upcasting by storing a Dog as an Animal. It calls the overridden sound method. Then it downcasts back to Dog to call fetch, a method only Dog has.

Java
class Animal {
    void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    void sound() {
        System.out.println("Dog barks");
    }
    void fetch() {
        System.out.println("Dog fetches the ball");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal myAnimal = new Dog();  // Upcasting
        myAnimal.sound();             // Calls Dog's sound method

        // Downcasting to access Dog-specific method
        if (myAnimal instanceof Dog) {
            Dog myDog = (Dog) myAnimal;
            myDog.fetch();
        }
    }
}
OutputSuccess
Important Notes

Always check with instanceof before downcasting to avoid errors.

Upcasting is useful for writing flexible code that works with many types.

Downcasting lets you use special features but should be done carefully.

Summary

Upcasting means treating a specific object as a more general type.

Downcasting means converting back to the specific type to use special features.

Use instanceof to safely downcast and avoid errors.