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 , not parent<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

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -