S.R Paul wrote:* why do the code prints 'Barking' instead of 'Generic animal sound'?
Because
a refers to a
Dog object, and you've overridden the
makeSound() method in class
Dog. It doesn't matter that the type of the variable
a is
Animal instead of
Dog - in fact, the whole point of
polymorphism is that it works this way.
S.R Paul wrote:* Is that casting not considered(or rejected silently) by the JVM?
The cast from
Dog to
Animal is unnecessary, because a
Dog is already an
Animal. But the rules of the language allow the cast. It doesn't do anything.
S.R Paul wrote:* Is casting for Ref types / object types?
Casting works on reference types as well as on primitive types. When you cast primitive types, in some cases
Java converts values (for example if you cast an
int to a
float, Java will convert the integer value to the corresponding floating-point value). When you cast reference types, no conversion is done.
What casting a reference type means is that you just tell the compiler "I have some object here, and I want you to treat it as if it of type X". Note that a check will still be done, but at runtime instead of at compile-time. If at runtime it turns out that the object is not really of type X, you'll get a ClassCastException.
Note that casting is in principle unsafe - you're deliberately telling the compiler to not do type checking.
You should only use casts when there's really no other way to write the code without a cast.