SpMidas SpMidas - 1 year ago 71
Java Question

How to correctly create a bounded generic class that extends a generic interface in Java

I'm,trying to implement a generic messaging system. Depending on the destination the class must implements different interfaces to be correctly deserialized by the server.

For this i have those interfaces:

public interface IBasicInput
public interface IBasicOutput
public interface IMessage <I,O>

And class implementations:

public class BasicInput1 implements IBasicInput
public class BasicOutput1 implements IBasicOutput
public class Type1Message<I extends IBasicInput,O extends IBasicOutput> implements IMessage<I, O> {

* @Override from IMessage
public void setIput(I input) {


* @Override from IMessage
public O getResult() {
return null;


The goal for this message is to have a Message that implements iMessage and the Input class must be an implementation of IBasicInput and the output an implementation of IBasicOutput

When instantiating this class

IMessage<IBasicInput,IBasicOutput> message = new Type1Message<BasicInput1,BasicOutput1>();

I got this error:

Type mismatch: cannot convert from
Type1Message to

I cant understand why. Type1Message implements IMessage and BasicInput and BasicOutput both implements the signature interfaces.

However,using the class instead the interface works fine
IMessage message = new Type1Message();


Answer Source

Generics types are not inherited. To make it compiles:

IMessage<? extends IBasicInput, ? extends IBasicOutput> message =
    new Type1Message<BasicInput1, BasicOutput1>();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download