Upcasting and Downcasting in Java
1. Upcasting
Definition:
Upcasting is the process of converting a subclass type to a superclass type. It is done
automatically in Java (implicit casting) and is also known as widening. When you upcast,
you can only access the methods and variables of the superclass, but if a method is
overridden in the subclass, the subclass's version will be called at runtime.
Example (Upcasting):
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
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 a = new Dog(); // Upcasting
a.sound(); // Calls Dog's overridden method
// a.fetch(); // Not allowed, Animal reference doesn't know
fetch()
}
}
Output:
Dog barks
2. Downcasting
Definition:
Downcasting is the process of converting a superclass type back to a subclass type. It is
done manually using a cast operator and is also known as narrowing. Downcasting is
needed when you want to access subclass-specific members from a superclass reference.
You must ensure the object is actually an instance of the subclass before downcasting,
otherwise a ClassCastException will occur.
Example (Downcasting):
public class Main {
public static void main(String[] args) {
Animal a = new Dog(); // Upcasting
a.sound(); // Calls Dog's overridden method
Dog d = (Dog) a; // Downcasting
d.fetch(); // Now accessible after downcasting
}
}
Output:
Dog barks
Dog fetches the ball
Key Differences between Upcasting and Downcasting:
Feature Upcasting Downcasting
Definition Converting subclass type to Converting superclass type
superclass type to subclass type
Type Widening Narrowing
Casting Implicit Explicit
Risk No risk of Possible ClassCastException
ClassCastException if not checked
Access Only superclass members Both superclass and
accessible subclass members
accessible
Purpose Generalization Specialization