我有這樣的代碼。將超類的對象轉換爲子類
超級類
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異常。
發佈異常跟蹤 –
您提供的代碼段不會拋出ClassCastException。 – Radiodef
你的代碼中沒有任何地方是你將一個超類轉換爲子類。你在哪裏得到ClassCastException? – TheLostMind