如何限制 class 在 Java 中使用某些类型?

How to restrict a class from taking certain types in Java?

我有一个基础 class 产品,它有五个子 class 产品(ComputerPart、Peripheral、Service、Cheese、Fruit)。其中每一个都有 2/3 subclasses.

然后我有一个 GenericOrder class 作为产品 class 中任意数量对象的集合。 GenericOrder 有一个名为 ComputerOrder 的子 class,它将 允许 ComputerPartPeripheralService添加到订单中。我花了很多时间试图弄清楚这一点,但无法得到合理的答案。请帮忙。这是我 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);
    }
}

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

public interface AllowableType {

}

计算机订单:

public class ComputerOrder extends GenericOrder<AllowableType> {

}  

产品class和系列:

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 接口。