如何将类的实例强制转换为子类并添加属性以便不抛出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.
}
}
我知道我可以创建一个Solid的新实例并从旧实例导入属性,但我想将属性添加到旧实例,所以比较==返回true。有什么想法吗?
答案 0 :(得分: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.