我很难创建类型安全的行为,我将使用一个通用示例来强调我的问题:
我有一个BoxCreator由以下定义的接口:
public interface BoxCreator{
    public Box create(int id ,List<Box> others);
}
和一个通用Box类(ABox可以包含其他几个Boxes),它具有 , 之类int getId()的方法Box getInternalBox(int id)。
假设我有一个类Shed implements BoxCreator,Container(其中容器只是一个通用接口,带有 add 和 remove 之类的操作)。我可以把新东西放在棚子里,它会把它们装在一个ShedBox工具箱里Box。
到目前为止一切都很好,当我尝试制作一些其他的类来做一些不同的事情时,问题就出现了,例如CoolShed extends Shed implements BoxCreator,它将把事情放入CoolBoxes (其中 extend ShedBox)。
现在它有效,但我在课堂上有几个可能“不漂亮”的向下转换CoolShed(从一般Box到)。CoolBox
我正在寻找的是一种制作方法
Shed<T extends ShedBox> implements BoxCreator<T>
然后在实施时CoolShed我会做类似的事情
CoolShed extends Shed<CoolBox> implemets BoxCreator<CoolBox>
我试图使各种类通用,但无法创建通用create方法,因为我无法T为此实例化或返回一个。所以我有点失落。
几个注意事项:
- 使用CoolShed了很多Shed逻辑,但我只是让它使用CoolBox类作为容器。
- 目前Shed有一个实例,BoxCreator所以在创建时CoolShed我只是创建CoolShed了新的创建者并且它可以工作。
- CoolShed只会有- CoolBox实例,但我真的不介意- ShedBox在- Shed课堂上扩展任何东西。
我只是找不到一个很好的解释来说明如何实现所需的行为,也无法判断我现有的演员表是否可以
我知道我的例子很长,我很乐意以任何方式使其更清楚。
编辑
使问题更清晰的代码模板:
public interface BoxCreator{
    public Box create(int id ,List<Box> others);
}
public interface Box{
    void put()
    void addAnother(Box box);
}
public class ShedBox implements Box{
    void put()
    void addAnother(Box box);
}
public class CoolBox extends ShedBox{ //has some extra features but moslty the same
    void put()
    void addAnother(Box box);
}
public interface Container {
    Box addValue(int value);
    Box getBox(int id);
    .
    .
}
public class Shed implements Container, BoxCreator {
    BoxCreator creator;
    SomeCollection<Box> boxes;
    Shed(){
        creator = this;
        .
        .
        .
    }
    Box addValue(int id){
        .
        .//some logic to get otherBox here
        .
        Box box = creator.createBox(id,otherBox);
    }
    Box getBox(int id);
    public Box create(int id ,Box other){
        return new ShedBox(id,others)
    }
}
public class CoolShed extends Shed implements BoxCreator {
    CoolShed(){
        creator = this;
        .
        .
        .
    }
    addValue(int id){
        Box boxAdded = super.add(id)
        .
        .
        .
        CoolBox box = (CoolBox)boxAdded; // The questionable cast
        .
        . //Some logic that involves CoolBox specific actions 
        .
    }
    public Box create(int id ,Box other){
        return new CoolBox(id,others)
    }
}