Search code examples
javacompiler-errors

Why does the compiler not give an error when making a "bad" cast?


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 ??
}

Solution

  • 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.