Implements an interface that return a generic type

I saw these:

I do understand why the compilator complains.

Anyway, if we only use the generic as a return value.

public interface Connection 
{
   <T extends Comparable<? super T>> T getVersion();
}

Then this implementation only gives a warning (I am using Java 7):

public class IoConnectionStub implements Connection
{
   public String getVersion()
   {
      return "1.0";
   }
}

Is this valid ? Or will it cause some problems ?

Thanks !

Jon Skeet
people
quotationmark

For a generic method, the caller can specify the type argument - so I should be able to use:

Connection foo = new IoConnectionStub();
Integer x = foo.<Integer>getVersion();

That's clearly not going to work in your case.

It sounds like if you really need this (which I think is slightly odd for a version property...) you would want to make the interface generic - that way IoConnectionStub could implement Connection<String> for example, and you'd end up with code of:

Connection<String> foo = new IoConnectionStub();
String version = foo.getVersion();

You couldn't ask for an Integer version number, because IoConnectionStub wouldn't implement Connection<Integer>.

people

See more on this question at Stackoverflow