Reputation: 1709
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 ??
}
Upvotes: 1
Views: 84
Reputation: 272467
Because in general, this cannot be detected at compile-time. For example:
Animal a = (someCondition) ? new Animal() : new Tiger();
((Tiger)animal).printText(animal);
Upvotes: 1
Reputation: 178421
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 return Tiger
as well. (Or the more common case, a method Animal getAnimal()
that might be overriden by subclasses to return a Tiger
).
At compile time, you could not possibly know if
Tiger tiger = (Tiger)getRandomAnimal();
is valid or not, this is known only at run time.
Upvotes: 3