Java泛型类,泛型类型扩展了多个其他类

Java泛型类,泛型类型扩展了多个其他类,java,class,generics,extend,Java,Class,Generics,Extend,我现在还不知道该怎么办,也许这是个愚蠢的问题,但我还是尝试一下 假设我有这些课程: class CellType1 { public void doSomething(){ // does something ClassType1 specific } } class CellType2 { public void doSomething(){ // does something ClassType2 specific } } c

我现在还不知道该怎么办,也许这是个愚蠢的问题,但我还是尝试一下

假设我有这些课程:

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
    }
}
这些类共享相同的函数,但函数本身的工作方式不同。现在我有一节课:

 class Map<CellTypes>{
   CellTypes cell;

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

    //...

    }
类映射{
细胞类型细胞;
//...
公共空间功能(){
细胞。剂量测定();
}
//...
}
该类的泛型类型稍后将成为三个上层类之一。在这个类中,我想访问这个特定CellType对象的doSomething()函数。我试过了

class Map<CellTypes extends CellType1, CellType2, CellType3> {
/*...*/
}
类映射{
/*...*/
}
但这限制了我对CellType1功能的了解。 如何在泛型类中使用来自不同类的函数? 也许有人比我有更好的主意! 我希望这是可以理解的

先谢谢你

编辑:


我需要将我的类映射作为泛型类,因为我需要创建不同的映射对象,并将需要使用的CellType类传递给它们

您可以创建一个界面:

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();
        }
    //...
}
类映射{
T细胞;
//...
公共空间功能(){
细胞。剂量测定();
}
//...
}
然后所有其他类实现这个接口。只有当方法签名在所有情况下都相同时,这才有效

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();
   } 
}

希望这有帮助

你不能。为什么他们没有一个通用的超类型?你不能让三个
CellType*
类扩展一个通用接口或类吗?让所有三个类都扩展或实现一个超类/接口,然后让你的地图的泛型就是那个超类型真棒,这就是我要找的!但遗憾的是,您只能在通用括号中使用“extends”关键字-如果我扩展intrface,它是否仍然有效?@kalu您不能
extends
a
interface
,这是一个语法错误。只有
可以扩展一个类。先看一下界面:我试过了,效果很好。不要忘记给未来的读者:当你实例化一个对象时,例如,of Map obj=new Map;您需要分配obj.cell=new CellType1();一个接口可以扩展另一个接口。是的。我还谈到了课程
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();
   } 
}