【问题标题】:How to restrict a class from taking certain types in Java?如何限制类在 Java 中采用某些类型?
【发布时间】:2015-03-12 13:31:45
【问题描述】:

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

然后我有一个GenericOrder 类,它充当 Product 类中任意数量的对象的集合。 GenericOrder 有一个名为 ComputerOrder 的子类允许将 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
}

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

干杯

【问题讨论】:

标签: java generics


【解决方案1】:

我想你想要这样的东西:

通用顺序:

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> {

}  

产品类别和系列:

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

【讨论】:

  • 非常感谢您回答我的问题...... AllowableType 接口会有什么?
  • @Shayaan 你的意思是AllowableType 接口会有哪些方法?它不必有任何方法。这只是一种限制允许与 ComputerOrder 一起使用的类型的方法。我想这就像marker interface
  • @Shayaan 太棒了!我很高兴能帮上忙。如果您觉得这是您问题的解决方案,请投票和/或接受答案。 :-)
  • 是的,这很有帮助........如果你不介意同样的任务,我确实有更多问题......我已经花了很长时间它......问题的措辞非常混乱......我必须创建另一个类 OrderProcessor,它将接受(),处理()和调度()各种类型的订单进出OrderPrcoessor 的内部集合
  • @Shayaan 根据您的问题,最好创建一个新问题并提供指向此帖子的链接(如果它有某种相关性)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-24
  • 1970-01-01
  • 2013-06-03
  • 1970-01-01
  • 2014-08-20
  • 1970-01-01
  • 2012-09-29
相关资源
最近更新 更多