Now, I have a method called parentClassMethod in both ParentClass and ChildClass classes(Overridden).
No you don't. You have a method named parentClassMethod
in ParentClass
and a method named ParentClassMethod
in ChildClass
. Since all Java identifiers are case-sensitive, there is no association between the two. ParentClassMethod
does not override parentClassMethod
from ParentClass
.
If (i) is working fine, why not (ii) or (iii)?
In (ii) and (iii) you are trying to cast an instance of ParentClass
to an instance of ChildClass
. That is not allowed, as a ChildClass
is-not-a ParentClass
, any more than an Object
is a String
.
In (i) you are trying to cast an instance of ChildClass
(stored in a reference declared as ParentClass
) to a ChildClass
, which is allowed.
When casting, it's the runtime type that counts (in other words, what T
is used in new T()
).