Reputation: 169
I can't wrap my head around it at the moment, maybe that's a stupid question but I give it a go.
Lets say I have these 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
}
}
These classes share the same functions but the functions themselves work differently. Now I have this Class:
class Map<CellTypes>{
CellTypes cell;
//...
public void function(){
cell.doSomething();
}
//...
}
This Class' Generic Type will later be one of the three upper classes. And in this class I want to access the doSomething()-Function for this specific CellType-Object. I've tried doing
class Map<CellTypes extends CellType1, CellType2, CellType3> {
/*...*/
}
But this limits me to the function/s of CellType1. How can I use the functions from different Classes in a Generic class? Maybe someone has a better idea than me! I hope this was understandable.
Thank you in advance.
EDIT:
I need to have my Class Map as a Generic Class, because I need to create different objects of map and pass them the CellType-class they need to be working with.
Upvotes: 0
Views: 1146
Reputation: 1241
You can create an interface:
interface CellType {
public void doSomething();
}
And implement the interface like this:
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();
}
//...
}
Upvotes: 1
Reputation: 735
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();
}
}
Hope this helps
Upvotes: 0
Reputation: 86754
public interface CanDoSomething {
public void doSomething();
}
Then all the other classes implement this interface. This works only if the method signature is the same in all cases.
Upvotes: 0