如何将类的实例转换为子类并添加属性,以免抛出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