Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create generic Interface restricted to own class

I would like to create a generic interface for those two classes but I'm not sure how to specify the generics the right way.

public class ThingA implements Thing {
    public ThingA createCopy(ThingA original);
}

public class ThingB implements Thing {
    public ThingB createCopy(ThingB original);
}

I tried it this.

public interface Thing<V extends Thing<V>> {
    public V createCopy(V original);

}

But I'm still able to do things like this, which shouldn't be allowed.

public class ThingB implements Thing<ThingA> {
    public ThingA createCopy(ThingA original);
}
like image 268
multiholle Avatar asked Aug 26 '13 11:08

multiholle


2 Answers

There is no this key-word generics (nor for methods parameters and return values declaration) and thus you cannot do exactly what you want.

In other words the interface will permit to ensure all the methods in the class use consistent types, but not to reference the class type itself.

like image 78
Guillaume Avatar answered Nov 16 '22 15:11

Guillaume


This is not possible. And it is not what Generics is for. Generics is for type safety, i.e. avoiding casts. If someone makes a class ThingB that implements Thing<ThingA> somehow, then great. It is perfectly type-safe. Why do you care? How does it impede what you are doing?

like image 41
newacct Avatar answered Nov 16 '22 16:11

newacct