Reputation: 997
I have an interface MessageHandler which takes a generic type T and an implementation MessageHandlerImpl which operates on concrete type CustomObject. And then I am using this in another client class as per shown below:
public interface MessageHandler<T> {
void validate(T t);
void process(T t);
default void handle(T t) {
validate(t);
process(t);
}
}
public class MessageHandlerImpl implements MessageHandler<CustomObject> {
@Override
public void validate(CustomObject message) {}
@Override
public void process(CustomObject message) {}
}
public class AnotherClientClass {
//option - 1
MessageHandlerImpl handler = new MessageHandlerImpl();
//option - 2
MessageHandler<CustomObject> handler = new MessageHandlerImpl();
public void getMessage() {
String messageStr = getMessageFromAnotherMethd();
CustomObject messageObj = convertToCustomObject(messageStr);
handler.handle(messageObj);
}
}
I have couple of questions here :
Upvotes: 0
Views: 83
Reputation: 77177
Generics are irrelevant here. Use the same guidelines you'd use to select the appropriate declared variable type in general.
More broadly, you have a poor design by calling new
at all. Instead, make the handler
a constructor parameter. In this case, definitely use the supertype MessageHandler<CustomObject>
(or, even better, MessageHandler<? super CustomObject>
or even Consumer<? super CustomObject>
).
Upvotes: 1