jeudi 15 décembre 2016

Java Generic Interface Return Type

Migrating to Java from C++.

I have a third party code with an interface I am required to implement which goes something like this.

public interface Foo<T>{
       public T doSomething();
}

I want to implement this interface so that I can call doSomething() and get 3 different classes A, B and C which extend a common base Z as below.

public class A extends Z{...};
public class B extends Z{...};
public class C extends Z{...};

I could not find any way of avoiding writing the following 3 classes.

public class ARet implements Foo<A>{...}
public class BRet implements Foo<B>{...}
public class CRet implements Foo<C>{...}

For the given interface Foo, is it not possible to write an implementation which returns T extends Z something which would look like public class Ret implements Foo<T extends Z>{...}. This does not appear to work. Is there any way of avoiding the 3 classes or there is no way around it?

Aucun commentaire:

Enregistrer un commentaire