将SuperClass的对象转换为子类

时间:2014-03-05 08:34:29

标签: java classcastexception

我有这样的代码。

超级

public class Actual {
    public int x = 123;
}

子类

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


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

所以问题是我可以将超类的对象转换为子类吗? 这个问题适合我试过的吗?

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);
    }
}

但它给出了Class Cast异常。

4 个答案:

答案 0 :(得分:5)

您可以将Child类转换为Super类,但反之亦然。 如果Vehicle是Super Class而Car是Subclass,则所有Cars(Child)都是Vehicle(Super),但并非所有Vehicle都是Car。

答案 1 :(得分:3)

  

我可以将超类的对象转换为子类吗?

不,你可以只做其他方式。您只能将子类对象分配给超类引用。

原因是,子类可以具有更多功能,更具体地解决问题。如果允许将超类对象放到子类中,那么超类对象将如何获得这些子类功能?

答案 2 :(得分:2)

没有可能这样做。你只能这样。 Actual s = new Super();Super sp = new Super();Actual a = new Actual();没有其他可能性。只有那个分配可能不会抛出classcast异常。

答案 3 :(得分:1)

这是创建超类和子类的对象的唯一方法:

Actual act = new Actual();
Actual actual = new Super();
Actual actual2 = new Sub();

Super super1 = new Super();
Super super2 = new Sub();

Sub sub = new Sub();  

没有其他办法。如果你试过它会给你编译时错误来构建你的类或者给出运行时错误java.lang.ClassCastException