Java 泛型 Class 具有扩展多个其他 类 的泛型

Java Generic Class with the Generic-Type extending multiple other classes

我现在不能全神贯注,也许这是个愚蠢的问题,但我试一试。

假设我有这些 Classes:

class CellType1 {

    public void doSomething(){
      // does something ClassType1 specific
    }
}

class CellType2 {

    public void doSomething(){
       // does something ClassType2 specific
    }
}

class CellType3 {

    public void doSomething(){
       // does something ClassType3 specific
    }
}

这些 classes 共享相同的功能,但功能本身的工作方式不同。现在我有了这个 Class:

 class Map<CellTypes>{
   CellTypes cell;

    //...
        public void function(){
           cell.doSomething();
        }

    //...

    }

此 Class' 通用类型稍后将成为三个上层 class 类型之一。在此 class 中,我想访问此特定 CellType 对象的 doSomething() 函数。我试过

class Map<CellTypes extends CellType1, CellType2, CellType3> {
/*...*/
}

但这将我限制为 CellType1 的 function/s。 如何在通用 class 中使用来自不同 Class 的函数? 也许有人比我有更好的主意! 我希望这是可以理解的。

提前致谢。

编辑:

我需要将我的 Class 地图作为通用 Class,因为我需要创建不同的地图对象并向它们传递它们需要工作的 CellType-class和。

您可以创建一个接口:

interface CellType {
    public void doSomething();
}

并像这样实现接口:

class CellType1 implements CellType {

    public void doSomething(){
      // does something ClassType1 specific
    }
}

class CellType2 implements CellType {

    public void doSomething(){
       // does something ClassType2 specific
    }
}

class CellType3 implements CellType {

    public void doSomething(){
       // does something ClassType3 specific
    }
}

Map class:

class Map<T extends CellType> {
   T cell;

    //...
        public void function(){
           cell.doSomething();
        }
    //...
}
public interface CanDoSomething {
    public void doSomething();
}

然后所有其他类实现这个接口。仅当方法签名在所有情况下都相同时才有效。

interface CellType {
   void doSomething();   
}
class CellType1 implements CellType {
    public void doSomething(){
        //your logic
    }
}
//similar implementation logic for CellType2 and CellType3
class Map {
   private CellType cellType;
   public Map(CellType cellType){
       this.cellType = cellType;
   }
   public void someFunc(){
      cellType.doSomething();
   } 
}

希望对您有所帮助