gpt4 book ai didi

java - 如何限制一个类在 Java 中采用某些类型?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:44:35 24 4
gpt4 key购买 nike

我有一个基类 Product,它有五个子类(ComputerPart、Peripheral、Service、Cheese、Fruit)。其中每一个都有 2/3 的子类。

然后我有一个GenericOrder类充当 Product 类中任意数量对象的集合。 GenericOrder有一个名为 ComputerOrder 的子类这将允许ComputerPart , PeripheralService添加到订单中。我花了很多时间试图弄清楚这一点,但无法得到合理的答案。请帮忙。这是我的 GenericOrder :

public class GenericOrder<T>{

private static long counter=1;
private final long orderID = counter++;
private List<T> orderItems;
public GenericOrder(){
orderItems = new ArrayList<T>();
}
// and so on with another constructor and add, get and set methods.
}

class ComputerOrder<T> extends GenericOrder{
//need help here
}

任何任何将不胜感激......

干杯

最佳答案

我想你想要这样的东西:

通用订单:

public class GenericOrder<T> {

private List<T> orderItems;

public GenericOrder() {
orderItems = new ArrayList<T>();
}

public void add(T item) {
orderItems.add(item);
}
}

让我们定义一个接口(interface),这将是 ComputerOrder 允许的唯一类型:

public interface AllowableType {

}

计算机订单:

public class ComputerOrder extends GenericOrder<AllowableType> {

}

产品类别和系列:

public class Product {

}

public class ComputerPart extends Product implements AllowableType {

}

public class Peripheral extends Product implements AllowableType {

}

public class Service extends Product implements AllowableType {

}

public class Cheese extends Product {

}

public class Fruit extends Product {

}

现在测试一下:

public void test() {
ComputerOrder co = new ComputerOrder();
co.add(new ComputerPart()); //ok
co.add(new Peripheral()); //ok
co.add(new Service()); //ok

co.add(new Cheese()); //compilation error
co.add(new Fruit()); //compilation error
}

如果我们想要将特定类型添加到 ComputerOrder,我们只需要让该类型实现 AllowableType 接口(interface)即可。

关于java - 如何限制一个类在 Java 中采用某些类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29011187/

24 4 0
文章推荐: android - react native 分析。 Systrace 未显示 JS 和 native 模块线程
文章推荐: java - 如何避免 Set 中的重复