What is Upcasting?
You'll learn: How to assign a subclass object to a superclass reference variable—a fundamental technique in polymorphic Java code.
The Core Idea
Upcasting is when you treat a subclass instance as if it were an instance of its superclass. You do this by assigning a subclass object to a superclass reference variable. It's called "upcasting" because you're moving up the inheritance hierarchy.
Remember from lesson 401 that subclass instances are type-compatible with their superclasses. Upcasting is simply using that compatibility explicitly.
The Syntax
class Animal {
void eat() {
System.out.println("Animal eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barking");
}
}
// This is upcasting:
Animal myAnimal = new Dog();
Here, new Dog() creates a Dog object, but we store it in an Animal reference variable. The Dog is-a Animal, so this works perfectly.
Why "Upcasting"?
Think of the inheritance tree like a family tree with Object at the top. Moving from Dog to Animal (its superclass) means moving upward in the hierarchy—hence "upcasting."
What You Can Access
Through the Animal reference, you can only call methods declared in Animal:
myAnimal.eat(); // Works fine
// myAnimal.bark(); // Compile error! Animal doesn't have bark()
Even though the object is a Dog at runtime, the reference type (Animal) determines what methods the compiler allows you to call.
Key Takeaway: Upcasting assigns a subclass object to a superclass reference variable, allowing you to treat specific types more generically—it's automatic, safe, and forms the foundation of polymorphism.