Take the 2-minute tour ×

Consider following Java classes:

public class Animal {
    public static void printText(Object obj) {

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 ??
share|improve this question
Exceptions are thrown. Compiler errors are printed. Don't confuse yourself. –  EJP Feb 3 '13 at 23:12
add comment

2 Answers

up vote 3 down vote accepted

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.

share|improve this answer
add comment

Because in general, this cannot be detected at compile-time. For example:

Animal a = (someCondition) ? new Animal() : new Tiger();

share|improve this answer
add comment

Your Answer


