Why is case 1 okay, and case 2 is not OK: since Dog is Animal , but not every Animal is Dog .
class Animal { } class Dog extends Animal { } class Cat extends Animal { } Dog fifi = new Dog(); Cat tommy = new Cat();
Note that casting does nothing for the object; in particular, it does not carry out any transformation of objects. Casting says only to the compiler: "I have this object here, and I know better than you what it is, I want you to treat it like type X and not tell me any error messages."
So, in a line like this:
Dog doggy = pet2;
the compiler will complain because it cannot be sure that pet2 is actually Dog ; he only knows that it is Animal - and not all Animal - Dog s. You can throw to tell the compiler not to complain about this:
But when you run the program, Java will still check if pet2 Dog valid, and if not, you get a ClassCastException .
(And the question in your name is exactly the opposite of what you mean, as the bizicop noted).
source share