Suyash Gulati wrote:but why? p refer to an object of type Child. it should compile, no? :/
The compiler only cares about what it knows at compile time, not at runtime. And that makes lots of sense! Now the assignment is nothing more but creating a new object of type
Child, but what if
p was initialized using a very complex method? So the compiler will prevent you from doing something stupid like assigning a new
String or
Dog to a
Parent reference variable.
But although your code compiles successfully you can still have an exception at runtime, e.g. when you try to cast a Parent object to a Child reference variable.
So in the code snippet you are referring to:
the compiler only knows
p is of type
Parent. It doesn't know/care about the actual object it's referring to. So when you want to assign it to
c, a reference variable of type
Child, an explicit cast is required. Because not all
Parent objects will be of type
Child and you have to tell the compiler you know what you are doing
If we switch the types of
p and
c no cast is required, because it happens implicitly. Because all Child objects will be of type
Parent. It's like: all dogs are animals, but not all animals are dogs. So if you want to have an animal do dog-things, you have to tell the compiler explicitly it's a dog (by using a cast). If at runtime the object you thought was a dog happens to be a cat (also an animal), you'll get a ClassCastException at runtime.
Hope it helps!
Kind regards,
Roel