java - How can I make extensions of interfaces compatible with generic parameters? -
follow this question, i'll try make self-contained.
suppose have interface called animal
, various reasons has generic type parameter representing implementing class:
public interface animal<a extends animal<a>>
i have sub-interface, dinosaur
, behaves in same way:
public interface dinosaur<d extends dinosaur<d>> extends animal<d>
now have class lizard
implements animal
:
public class lizard implements animal<lizard>
and subclass, trex
, implements dinosaur
:
public class trex extends lizard implements dinosaur<trex>
these 4 declarations produce error. because class trex
implements interface animal
twice, different type parameters: since extends lizard
, implements interface animal<lizard>
, , since implements dinosaur<trex>
, implements animal<trex>
.
animal<trex>
not subinterface of animal<lizard>
, though trex
subclass of lizard
, compiler error.
i'm sure there's way around using wildcards, can't work out is.
here's can compile same error:
public class interfacetest { private interface animal<a extends animal<a>> {} private interface dinosaur<d extends dinosaur<d>> extends animal<d> {} private class lizard implements animal<lizard> {} private class trex extends lizard implements dinosaur<trex> {} }
this because class trex implements interface animal twice, different type parameters
yup, case, , there's no way around directly - it's technical limitation because generics implemented using erasure. you can never implement same interface on more 1 class different generic parameters. when generic types erased you'd end extending 2 interfaces identically, no way distinguish between methods making use of different generic types, , no way runtime determine method execute.
for particular use case there's workaround means don't have implement same interface different type parameters, without more details it's impossible might be.
edit: looking @ linked question, looks solve problem using other answer (the 1 haven't accepted) specifies return value in way rather declaring on class:
public <t extends jnumber> t add(t addend);
this should mean don't need declare generic type parameter on classes , interfaces, , shouldn't have issue.
Comments
Post a Comment