Hello everyone. In the following code,
I'm surprised that each of the following two statements compiles:
Of course, each of these 2 statements will cause a ClassCastException at runtime.
I realize that the compiler has to go with the reference type. All that matters is that new Animal() is of type Animal. And
you should be able to cast an Animal reference to an Animal subclass. You're telling the compiler to trust you.
Still, in this case, it seems that "new Animal()" would have to be of type Animal. I can't think of any unusual case (e.g. new Animal() { <anonymous class> } ) that would return a Cat.
So it seems to me that the compiler is following the general rule of allowing us to cast an Animal to a Cat, even though in this case, I think it would be impossible
for the statement to run successfully. So maybe this is a special case that the compiler should catch?
Thanks!