Course contentsShow
← Java
Lesson 443 of 2,87011. Polymorphism and Dynamic DispatchFree lesson

What is Downcasting?

Understanding downcasting as casting a superclass reference back to a subclass type.

What is Downcasting?

You'll learn how to cast a superclass reference back to its original subclass type—a process called downcasting.

The Core Idea

When you upcast an object (assign a subclass instance to a superclass reference), Java "forgets" the subclass-specific members at compile time. Downcasting is the reverse operation: you explicitly cast a superclass reference back to a subclass type to regain access to those subclass-specific features.

Think of it like this: you put a novel into a generic "book" box. Everyone sees it as just a "book." To read the novel-specific features (like chapter titles), you must take it out and say, "This is specifically a novel, not just any book."

Why You Need It

After upcasting, you can only call methods that exist in the superclass. If you need to access a subclass-specific method or field, you must downcast:

Animal myAnimal = new Dog();  // Upcasting (implicit)
myAnimal.eat();               // Works: eat() is in Animal

// myAnimal.bark();           // Compile error: Animal has no bark()

Dog myDog = (Dog) myAnimal;   // Downcasting (explicit cast)
myDog.bark();                 // Now works!

Notice the explicit cast syntax: (Dog) tells Java "trust me, this Animal reference really points to a Dog object."

The Risk

Unlike upcasting, downcasting can fail at runtime if the actual object isn't the type you're casting to. This is why downcasting requires an explicit cast—you're taking responsibility for ensuring correctness (you'll learn safety checks with instanceof soon).

Key Takeaway: Downcasting is an explicit cast from a superclass reference back to a subclass type, letting you access subclass-specific members—but you must ensure the object really is that subclass type.