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.