Consider following Java classes:
public class Animal {
public static void printText(Object obj) {
System.out.println(obj.toString());
}
}
class Tiger extends Animal {
// Contains some unimportant methods.
}
And now, when the following is typed into the main method, the compiler won’t give any errors even though that cast will result in an error. Why?
public static void main(String[] args) {
Animal animal = new Animal();
((Tiger)animal).printText(animal); // <= ?? no error in the compiler ??
}
In your example, it might be easy to know that the cast is wrong – but in the general case it is not.
What if you had a method
Animal getRandomAnimal()that might returnTigeras well. (Or the more common case, a methodAnimal getAnimal()that might be overriden by subclasses to return aTiger).At compile time, you could not possibly know if
is valid or not, this is known only at run time.