I've got classes
public class DiaryItem extends AbstractInfoElement { ... };
public class EventItem extends AbstractInfoElement { ... };
public class StickerItem extends AbstractInfoElement { ... };
public class TodoItem extends AbstractInfoElement { ... };
I've got overridden methods to do something with this parameters:
class DBEngine {
public long add(EventItem item){ ... };
public long add(StickerItem item){ ... };
public long add(TodoItem item){ ... }
}
Then I realized template class to manipulate types in generic way
public class AddItemCommand<T extends AbstractInfoElement>{
private final T item;
public AddItemCommand(T item) {
this.item = item;
}
void doSmth() {
add(item);
}
}
I suppose compiler resolve T as needed type, but I got issues:
Error:(78, 45) error: no suitable method found for add(T)
method DBEngine.add(DiaryItem) is not applicable
(argument mismatch; T cannot be converted to DiaryItem)
method DBEngine.add(EventItem) is not applicable
(argument mismatch; T cannot be converted to EventItem)
method DBEngine.add(StickerItem) is not applicable
(argument mismatch; T cannot be converted to StickerItem)
method DBEngine.add(TodoItem) is not applicable
(argument mismatch; T cannot be converted to TodoItem)
where T is a type-variable:
T extends AbstractInfoElement declared in class AddItemCommand
My goal was to avoid overcoding in those cases:
AddItemCommand<DiaryItem> cmdDiary = new AddItemCommand<DiaryItem>(new DiaryItem);
cmdDiary.doSmth();
should call
DBEngine.add(DiaryItem item);
and
AddItemCommand<TodoItem> cmdTodo = new AddItemCommand<TodoItem>(new TodoItem);
cmdTodo.doSmth();
should call
DBEngine.add(TodoItem item);
That's all, but doesn't work ... Those issues are at compile time...
BTW... Excuse my poor english