public class InheritanceDemo {
public static void main(String[] args) {
ParentClass p = new ParentClass();
ChildClass c = new ChildClass();
//Casting ChildClass to ParentClass
ParentClass pc = new ChildClass();
pc.parentClassMethod(); //Output: Parent Class Method (as expected)
//Again Casting Parent Class to ChildClass explictly
//Question 1 for this code
ChildClass cp = (ChildClass) pc;
cp.parentClassMethod(); //Output: Parent Class Method (unexpected)
ChildClass cc1 = (ChildClass) new ParentClass();
cc1.parentClassMethod(); //Compiles, but Run Time Error
ChildClass cc2 = (ChildClass) p;
cc2.parentClassMethod(); //Compiles, but Run Time Error
}
}
class ParentClass {
public void parentClassMethod(){
System.out.println("Parent Class Method");
}
}
class ChildClass extends ParentClass {
public void ParentClassMethod(){
System.out.println("Parent Class Method From Child Class");
}
public void ChildClassMethod(){
System.out.println("Child Class Method");
}
}
Question1:
Now, I have a method called parentClassMethod
in both ParentClass
and ChildClass
classes(Overridden). When I cast the ParentClass
to ChildClass
and then call the parentClassMethod, why is it executing the ParentClass
method instead of the method from ChildClass
if cp is refering to ChildClass
?
Question2:
(i) ChildClass cp = (ChildClass) pc;
(ii) ChildClass cc1 = (ChildClass) new ParentClass();
(iii) ChildClass cc2 = (ChildClass) p;
If (i) is working fine, why not (ii) or (iii)?
Because I am casting from ParentClass
to ChildClass
in both the cases?