Search code examples
javaclasscastexception

Converting Object of SuperClass to Sub Class


I have some Code like this.

Super Class

public class Actual {
    public int x = 123;
}

Sub classes

public class Super extends Actual{
    public int x = 999;
    public int y = 12345;
}


public class Sub extends Super {
    public int x = 144;
}

so Question is Can i convert Object of Super Class into the Sub class? is this Right for this Question what i have tried?

public class Mid1Prob1 {
    public static void main(String[] args) {
        System.out.println("Testing...");
        int x = 3;
        Actual actual = new Super();
        System.out.println(actual.x);


        Super super1 = new Super();
        System.out.println(super1.x);


        Actual act = new Actual();

        act = new Sub();
        System.out.println(act.x);
    }
}

but its giving Class Cast exception.


Solution

  • You can cast Child classes to Super classes but not vice versa. If Vehicle is Super Class and Car is a Subclass then all Cars (Child) is a Vehicle (Super) but not all Vehicle is a Car.