When working with inheritance in Java, you’ll often hear two terms:
Upcasting and Downcasting.
Don’t worry — it’s not as complicated as it sounds.
First, let’s understand the idea
In Java, a child class inherits from a parent class.
Example:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
Here:
Animal -> Parent class
Dog -> Child class
What is Upcasting?
Upcasting means:
Converting a child class object into a parent class reference
Example:
Animal a = new Dog(); // Upcasting
a.sound();
What’s happening here?
Dog object is created
But it is stored in Animal reference
Important point:
You can only access parent class methods
a.sound(); // Works
// a.bark(); // Error
Even though the object is Dog, Java only allows what Animal knows.
Why use Upcasting?
- Helps in polymorphism
- Makes code flexible and reusable
What is Downcasting?
Downcasting means:
Converting parent reference back to child type
Example:
Animal a = new Dog(); // Upcasting
Dog d = (Dog) a; // Downcasting
d.bark();
What’s happening?
We tell Java: “Hey, this Animal is actually a Dog”
So now we can use child methods
Important: Be careful
Downcasting can cause errors if done wrongly.
Animal a = new Animal();
Dog d = (Dog) a; // Runtime error
This will crash because:
a is NOT a Dog
Safe way to Downcast
Use instanceof:
if (a instanceof Dog) {
Dog d = (Dog) a;
d.bark();
}
- instanceof is used to check whether an object belongs to a particular class or not.
- It returns:
true → if object belongs to that class
false → if it doesn’t
Simple Real-Life Analogy
Think like this:
Animal = General category
Dog = Specific type
Upcasting:
Treating a Dog as an Animal
("This is an animal")
Downcasting:
Checking and saying
("This animal is actually a dog")
Final Summary
Upcasting = Child -> Parent (safe, automatic)
Downcasting = Parent -> Child (manual, risky)
Use instanceof before downcasting
Top comments (0)