java - 有没有办法在不使用 instanceof 的情况下强制方法使用子类构造函数?

标签 java

对不起,如果我的格式不好,第一次在 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/

相关文章:

java - 在代码 : Implementation of "database" where a query and result is obtained from proprietary CLI commands 中表示命令行界面命令

java 服务器守护进程部署选项

java - 运行 JavaFX Maven 插件(修复类路径)后 javafx.application.Application 出现 NoClassFoundException

java - 反向金字塔java模式与 "!!"

java - HTTP 安全配置authorizeRequests() 出现 Sonar 严重缺陷

java - 使用java将pdf文档转换为word文档

java - 为什么这个程序打印 "Hello"? (Java中函数指针如何转换为Runnable.run())

java - spring.profiles.active 未兑现

java - rmi 服务器抛出 AccessControlException

java - 如何解决构建Conductor过程中出现的问题