将SuperClass的对象转换为子类

我有这样的代码。

超级

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 Castexception。

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

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

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

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

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

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

 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