对不起,如果我的格式不好,第一次在 StackOverflow 上。 我有一个 FruitBuilder 类,用于一组相同类型的对象,这些对象都是 Fruit 类的所有扩展,FruitBuilder 包含一组变量,如下所示:
public Apple redApple = new Apple(size, color, price);
public Orange bigOrange = new Orange(size, color, price);
public Pear greenPear = new Pear(size, color, price);
我有一个名为 makeFruit 的复制方法,它创建一个新水果并将其添加到 ArrayList fruits 中,如下所示:
public Fruit makeFruit(Fruit f){
Fruit fruit = new Fruit(f.size, f.color, f.price);
fruits.add(fruit);
return fruit;
}
这工作正常,除了它创建了一个新的 Fruit 而不是所需的子类,我可以通过使用一系列 instanceof 检查然后根据具体情况强制子类使其工作:
public Fruit makeFruit(Fruit f){
if (f instanceof Apple){
Apple apple = new Apple(f.size, f.color, f.price);
fruits.add(apple);
return apple;
//snip
}
}
有没有更简单的方法呢?
最佳答案
使用clone()
-- 它正是为此目的而设计的:
public Fruit makeFruit(Fruit f) {
Fruit fruit = (Fruit)f.clone();
fruits.add(fruit);
return fruit;
}
有几种方法可以使 clone()
为您的类工作。最简单的是让 Fruit
实现 Cloneable
:
public class Fruit implements Cloneable {
...
}
这是一个marker interface ,因此您无需实现任何方法。
关于java - 有没有办法在不使用 instanceof 的情况下强制方法使用子类构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19651516/