Search code examples
javainheritancetypescastingpolymorphism

why i can not cast parent to child some specific scenario


I have two classes, one Animal and one Bear. example code

class Animal {}
class Bear extends Animal {}

when I write code like

Animal animal = new Bear();
Bear bear = (Bear) animal;

I also know that the first one is upcasting and second one is downcasting and works fine.

but my question is when I code like:

Animal animal = new Animal();
Bear bear = (Bear) animal;

it throughs a ClassCastException.

I want to know why this happens.


Solution

  • Casting in Java can't change an object type. It just tells the compiler that it's OK to treat a certain object as a certain type, since in runtime that's what's going to be there.

    In the first example, bear is really a Bear instance, so the casting works just fine.
    In the second example, it isn't, so you get a ClassCastException.