Originally posted by sravanthi pulukuri:
Can you elucidate it with an example??
Hi,
See the code to get it in better way:
Note: Compiler does not know the runtime type, because object creation
and its reference assignment is matter of runtime. Compiler only
wants that what assignment you are doing is castable. It can't see what
object the ref variable is pointing to. K&B says, here compiler relies on
us, in fact it has no other alternative except relying on us here.
But JVM see that we are trying to assign Animal object to Dog ref variable
hence ClassCastExeption. Dog is Animal for sure but Animal is not required
to be Dog only (It can be Horse,
Cow, Buffalo
etc)
By the way
John Stone gave nice example with String and Object,
and very similar question I faced in exam too.
Thanks,