2017-07-13 71 views
0

我现在不能包围我的头,也许这是一个愚蠢的问题,但我给它一个。Java通用类与通用类扩展多个其他类

可以说我有这些类:

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的功能/ s。 如何使用泛型类中不同类的函数? 也许有人比我有更好的主意! 我希望这是可以理解的。

预先感谢您。

编辑:

我需要让我的类映射为一个泛型类,因为我需要创建地图的不同的对象,并通过他们的单元格类型级的他们需要与合作。

+1

你不能。为什么他们没有共同的超类型? – shmosel

+1

你不能让三个'CellType *'类扩展一个通用接口或类吗? – jensgram

+0

让所有三个类都扩展或实现一个超级类/接口,然后让你的地图的泛型为超类型 –

回答

1

您可以创建一个接口:

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 Map<T extends CellType> { 
    T cell; 

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

太棒了,这就是我一直在寻找的!但遗憾的是,你只能在通用括号中使用“extends”关键字 - 如果我扩展了intrface,它还能工作吗? – kalu

+0

@kalu你不能'扩展''interface',它是一个语法错误。只能'扩展'一个类。先阅读关于接口:https://docs.oracle.com/javase/tutorial/java/concepts/interface.html – Blasanka

+0

@kalu你可以!我编辑了我的答案。 –

0
public interface CanDoSomething { 
    public void doSomething(); 
} 

然后所有其他类实现这个int erface。只有方法签名在所有情况下都是相同的,这才有效。

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

希望这有助于