如何限制类在Java中使用某些类型?
我有一个基类产品,它有五个子类(计算机部件、外围设备、服务、奶酪、水果)。每一个都有2/3的子类 然后我有一个如何限制类在Java中使用某些类型?,java,generics,Java,Generics,我有一个基类产品,它有五个子类(计算机部件、外围设备、服务、奶酪、水果)。每一个都有2/3的子类 然后我有一个GenericOrder类,它充当产品类中任意数量对象的集合GenericOrder有一个名为ComputerOrder的子类,该子类将只允许将ComputerPart、Peripheral和Service添加到订单中。我花了相当长的时间试图弄明白这一点,但没有得到一个合理的答案。请帮忙。以下是我对GenericOrder的了解: public class GenericOrder<
GenericOrder
类,它充当产品类中任意数量对象的集合GenericOrder
有一个名为ComputerOrder
的子类,该子类将只允许将ComputerPart
、Peripheral
和Service
添加到订单中。我花了相当长的时间试图弄明白这一点,但没有得到一个合理的答案。请帮忙。以下是我对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
}
公共类GenericOrder{
专用静态长计数器=1;
private final long orderID=counter++;
私人物品清单;
公共通用订单(){
orderItems=new ArrayList();
}
//依此类推,使用另一个构造函数和add、get和set方法。
}
类ComputerOrder扩展了GenericOrder{
//这里需要帮助吗
}
任何人都将不胜感激
干杯我想你想要这样的东西: 一般订单:
public class GenericOrder<T> {
private List<T> orderItems;
public GenericOrder() {
orderItems = new ArrayList<T>();
}
public void add(T item) {
orderItems.add(item);
}
}
电脑订购:
public class ComputerOrder extends GenericOrder<AllowableType> {
}
现在测试它:
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
接口。使用自定义接口作为要添加到泛型的类型/类的标记,并在泛型声明中使用接口名称(确保选择的类与层次结构相关)可能相关,请参见您需要让这三个类继承一个接口,然后是类GenericOrder
。如果您有机会让T
成为原语,那么您需要定义显式类而不需要惰性,即类IntOrder
,类FloatOrder
,等等。非常感谢您的支持请回答我的问题……AllowableType接口将有什么?@Shayaan你是说AllowableType
接口将有什么方法吗?它不必有任何方法。这只是一种限制允许在ComputerOrder中使用什么类型的方法。我想这就像一个命令。@Shayaan太好了!我很高兴能帮上忙。如果你觉得如果这是您问题的解决方案,请向上投票和/或接受答案。:-)是的,这很有帮助……如果你不介意的话,我还有更多的问题……我花了很多时间在这上面……问题的措辞非常混乱……我必须创建另一个类OrderProcessor,它将接受()、进程()和调度()各种类型的订单输入和输出到OrderPrcoessor@Shayaan根据你的问题是什么,最好创建一个新的问题,并提供一个链接到这篇文章,如果它是相关的。
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
}