我有一些像这样的代码。
超级类
问题是,我能否将超类对象转换为子类对象?对于我尝试的这个问题,这样做是否正确?
但是它给出了“类转换异常”。
超级类
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);
}
}
但是它给出了“类转换异常”。