Search code examples
javacastingtype-conversiondowncast

Java: Casting ParentClass and ChildClass (Downcast Runtime Error)


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?


Solution

  • 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()).