Reputation: 527
I would like to use one method for two types and I tried like this:
private <T extends Base> boolean isNeeded(String name, T receivedItem) {
Base item = null;
if (receivedRequest.getClass().equals(Derived1.class)) {
item = (Derived1) receivedItem;
} else if (request.getClass().equals(Derived2.class)) {
item = (Derived2) receivedItem;
}
callMethodDoSomething(item.getData().getSpecificData());
}
But I do not know how to call a method which is only in the derived classes. Which is the best and safest way to do it?
Upvotes: 0
Views: 84
Reputation:
Why not just
boolean isNeeded(Base base) {
return callMethodDoSomething(base.getData().getSpecificData());
}
(Also skip the 'name' parameter since it is not used)
Upvotes: 1
Reputation: 12493
That's what method overloading is for.
boolean isNeeded(String name, Derived1 item) {
return callMethodDoSomething(
item.getData().getSpecificData());
}
boolean isNeeded(String name, Derived2 item) {
return callMethodDoSomething(
item.getData().getSpecificData());
}
Upvotes: 1