如何將類的實例轉換爲子類並添加屬性,以免拋出ClassCastException?例如:將屬性添加到超類實例以使其成爲子類實例
public class Shape {
private int length;
private int width;
public Shape(int length, int width) {
this.length = length;
this.width = width;
}
}
public class Solid extends Shape {
private int height;
public Solid (int length, int width, int height) {
super(length, width);
this.height = height;
}
}
public class Test {
public static void main(String[] args) {
Shape shape = new Shape(1, 2);
//Do something to change the shape instance to solid instance.
Solid solid = (Solid) shape;//Makes it does not throw ClassCastException.
System.out.println(shape instanceof Solid);//Makes it print true.
System.out.println(shape == solid);//Makes it print true.
}
}
我知道我可以創建立體的新實例和舊實例導入的屬性,但我想添加屬性到舊的實例代替用==比較返回true。有任何想法嗎?
你不能改變的執行時間一旦你創建了一個對象的類型。如果你想創建一個'Solid'的實例,只需將你的第一行改爲'new Solid(1,2,3)'。說實話,你想要達到什麼目前還不清楚。 –
@RcExtract請更新您的問題,以包括您想從外部庫添加額外屬性到現有類的原因?當這個新的屬性沒有被原始類/庫定義時,誰會對這個新屬性做出反應?這聽起來像是一個XY問題,也許你應該說明你的原始問題。 – Progman