MJ#30: Upcasting and Downcasting in Java

Upcasting: Upcasting refers to the process of casting an object to its superclass type. It happens automatically in Java when you assign an object of a subclass to a variable of its superclass type. Upcasting is safe and does not require an explicit cast.

class Animal {

void eat() {
System.out.println("Animal is eating");
}
}

class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}

public class Example {
public static void main(String[] args) {
Dog myDog = new Dog(); // Creating an object of subclass (Dog)
Animal animal = myDog; // Upcasting (implicitly)

animal.eat(); // Accessing the eat() method from Animal
// animal.bark(); // Error: bark() is not a method of Animal
}
}

n this example, myDog is upcast to Animal type. The variable animal of type Animal can only access the methods and members of the Animal class, even though the actual object is of type Dog.

Downcasting: Downcasting is the opposite of upcasting. It involves casting an object of a superclass type back to its original subclass type. Downcasting requires an explicit cast and may result in a ClassCastException if the object is not of the expected type.

class Animal {

void eat() {
System.out.println("Animal is eating");
}
}

class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}

public class Example {
public static void main(String[] args) {
Animal animal = new Dog(); // Creating an object of superclass (Animal)

if (animal instanceof Dog) {
Dog myDog = (Dog) animal; // Downcasting (explicit)
myDog.bark(); // Accessing the bark() method from Dog
}
}
}

In this example, animal is initially of type Animal, but it’s assigned an object of type Dog. To access the bark() method specific to Dog, we need to downcast animal to Dog. The instanceof operator is used to check whether downcasting is safe, and the cast is performed conditionally.

Note: Downcasting should be done carefully with proper checks to avoid runtime ClassCastException. It is advisable to use instanceof before downcasting to ensure the object is of the expected type.

Leave a comment