Generics + Interfaces in Java -
consider example:
class parent<t> implements myinterface<t> {...} class child1 extends parent<concretetype1>{...} class child2 extends parent<concretetype2>{...}
and following factory:
public class factory<t> { public static <t> parent<t> getchild(type type) { switch (type) { case value1: return new child1(); case value2: return new child2(); } } }
the type
parameter enum
.
now,
- if leave things above, following error: cannot convert
child1
parent<t>
- if remove generics, leaving
parent
, notparent<t>
, warning
how can fix issue?
the method not know exact type of t
, return parent<?>
:
public static parent<?> getchild(type type) { ... }
or, extend type
class construct children, , have control on exact output:
public static <t> parent<t> getchild(type<t> type) { return type.createchild(); }
Comments
Post a Comment