2017-10-14 68 views
0

如何將類的實例轉換爲子類並添加屬性,以免拋出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。有任何想法嗎?

+4

你不能改變的執行時間一旦你創建了一個對象的類型。如果你想創建一個'Solid'的實例,只需將你的第一行改爲'new Solid(1,2,3)'。說實話,你想要達到什麼目前還不清楚。 –

+0

@RcExtract請更新您的問題,以包括您想從外部庫添加額外屬性到現有類的原因?當這個新的屬性沒有被原始類/庫定義時,誰會對這個新屬性做出反應?這聽起來像是一個XY問題,也許你應該說明你的原始問題。 – Progman

回答

1

您可以通過添加一個構造親近你想要什麼Solid接受Shape作爲參數:

public Solid (Shape shape) { 
    this(shape.getLength(), shape.getWidth(),0); 
} 

和測試是:

Shape shape = new Shape(1, 2); 
shape = new Solid(shape); 
System.out.println(shape instanceof Solid);//prints true. 
Solid solid = (Solid) shape; 
System.out.println(shape == solid);//prints true. 
+0

我不想要創建第二個實例。 這是我的情況。一個程序創建一個類A的實例。然後,我想向它添加屬性,但是我不能在程序的擴展中創建一個類A的新實例,因爲它應該由程序本身創建。我可以添加屬性到由程序創建的實例A中,而不用創建包裝類? – RcExtract

+0

另一種選擇是隻使用Solid:具有'Solid(int length,int width)'構造函數,它實際上是一個'Shape',並添加一個屬性或標誌,例如'isSolid' – c0der

相關問題