In Java, downcasting refers to the process of converting a reference from a superclass type to a subclass type. This concept is relevant in the context of inheritance, where a subclass extends a superclass and potentially adds more behavior or state.
However, downcasting in Java should be done with caution because it can lead to a 'ClassCastException' if the actual object referred to by the superclass reference is not of the subclass type. Java checks the correctness of downcasting at runtime to prevent invalid downcasts.
Consider the following class hierarchy:
class Animal
{
public void eat()
{
System.out.println("Animal is eating");
}
}
class Dog extends Animal
{
public void bark()
{
System.out.println("Dog is barking");
}
}
class Main
{
public static void main(String[] args)
{
// Upcasting - no explicit cast required
Animal animalRef = new Dog();
// Downcasting - explicit cast is required
Dog dogRef = (Dog)animalRef;
dogRef.bark(); // This will output "Dog is barking"
}
}
In this example, we first perform upcasting when we assign a 'Dog' object to an 'Animal' reference. Then we perform downcasting by casting the 'Animal' reference back to a 'Dog'. Since the actual object is a 'Dog', this downcast is valid and allows us to call the Dog-specific bark() method.
To prevent 'ClassCastException' at runtime, you can use the instanceof operator to check the actual type of the object before downcasting for safety:
Animal animal = new Animal();
if (animal instanceof Dog)
{
Dog dog = (Dog)animal;
dog.bark();
}