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

ClassCastException: When Downcasting Fails

Understanding runtime failures when downcasting to an incompatible type.

ClassCastException: When Downcasting Fails

You'll learn what happens at runtime when you try to downcast to an incompatible type.

The Risk of Downcasting

Remember that downcasting requires an explicit cast because the compiler can't verify the actual object type at compile-time. When you run your code, Java performs a runtime check: is this object really an instance of the type I'm casting to? If the answer is no, Java throws a ClassCastException.

Think of it like trying to force a square peg into a round hole. The compiler lets you attempt the cast (because it's syntactically valid), but at runtime, Java discovers the object doesn't fit and stops execution with an error.

When Does It Fail?

Animal animal = new Animal();  // Just an Animal, not a Dog

// This compiles but fails at runtime:
Dog dog = (Dog) animal;  // ClassCastException!

The reference animal points to an Animal object—it was never a Dog to begin with. You can't magically turn an Animal into a Dog just by casting.

Safe Scenario vs Unsafe Scenario

// SAFE - the object really is a Dog
Animal animal1 = new Dog();    // Upcasting
Dog dog1 = (Dog) animal1;      // Downcasting succeeds ✓

// UNSAFE - the object is just an Animal
Animal animal2 = new Animal();
Dog dog2 = (Dog) animal2;      // ClassCastException at runtime ✗

The key difference: in the safe scenario, the object was created as a Dog, even though it was upcast to Animal. In the unsafe scenario, the object was created as just an Animal.

Key Takeaway: Downcasting fails with ClassCastException when the actual runtime object is not an instance of the target type. The compiler allows the cast syntax, but Java checks type compatibility at runtime and throws an exception if the cast is invalid.