2017-10-14 99 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