public class Animal {
public void eat() {}
}
public class Dog extends Animal {
public void eat() {}
public void main(String[] args) {
Animal animal = new Animal();
Dog dog = (Dog) animal;
}
}
The assignment Dog dog = (Dog) animal;
does not generate a compilation error, but at runtime it generates a ClassCastException
. Why can't the compiler detect this error?
As explained, it is not possible. If you want to use a method of the subclass, evaluate the possibility to add the method to the superclass (may be empty) and call from the subclasses getting the behaviour you want (subclass) thanks to polymorphism. So when you call d.method() the call will succeed withoug casting, but in case the object will be not a dog, there will not be a problem