クラスのインスタンスをサブクラスにキャストしてプロパティを追加すると、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を返したように、古いインスタンスにプロパティを追加します。何か案は?あなたが引数としてShape
を受け入れSolid
にコンストラクタ追加することによって、近いあなたが欲しいものを得ることができます
あなたは、実行時間を変更することはできません。いったん作成したオブジェクトのタイプ。 'Solid'のインスタンスを作成したい場合は、最初の行を' new Solid(1、2、3) 'に変更してください。正直言って、あなたが達成しようとしていることは非常に不明です。 –
@RcExtract質問を更新して、外部ライブラリから既存のクラスに追加のプロパティを追加する理由を含めるようにしてください。元のクラス/ライブラリで定義されていない場合、誰がこの新しいプロパティに反応しますか?これはXY問題のように聞こえるかもしれません。元の問題を述べるべきかもしれません。 – Progman