Why casting is not possible from child to parent

Viewed 76

I have a class Animal which has one child Dog.

class Animal {
    public void makeSound() {
        System.out.println("Animal sound");
    }
}

class Dog extends Animal {
    @Override
    public void makeSound() {
        super.makeSound();
    }
}

public static void main(String[] args) {
    Dog dog = (Dog) new Animal(); // It compiles, but throws runtime exception.
    dog.makeSound();
}

Here if we will cast child to parent, it will compile, but it will throw runtime exception - ClassCastException. Of course, there can be a case when the child will have a field or method which the parent doesn't. That's why we can't cast Dog to Animal. Also, there's no IS-A relationship. But why the cast is not possible, in case parent and child classes have only the same fields and methods?
I've got asked this question in the interview)

Thank you.

1 Answers

When the compiler sees that you are trying to cast the Animal object into a Dog, it "knows" that Dog is underneath Animal in the hierarchy, so it is possible that the animal is a dog, so it allows it. However, at runtime, it turns out that it is just an Animal, and is not a Dog, so the cast fails.

This is a weird case in which it is obvious in reading the program that the Animal is just an Animal and not a Dog because it was just created with "new Animal()", but the compiler doesn't know that--it just knows that it is an Animal. Compilers are smart, but they can't know everything. I hope that makes sense.

Related