Difference between using wildcards and declaring generic type in abstract method in Java -
i'm trying understand generic types in java, , in theory looks understandable, when need apply real code have problem. want declare abstract method return generic type. let's assume have empty interface called magicable , 2 class implements it: magican , witch. wonder difference between 3 declarations:
/*1*/protected abstract <t extends magicable> list<t> getmagicables(); /*2*/protected abstract list<? extends magicable> getmagicables(); /*3*/protected abstract list<magicable> getmagicables();
in first case have problem when want implement body of method in class extends abstract class:
@override protected list<magican> getmagicable() {..}
i have warning message:
type safety: return type list<magican> getmagicable() type magicanservice needs unchecked conversion conform list<magicable> type magicableservice.
in second case don't have warning, have problem in abstract class in declared above abstract method:
public void <t extends magicable> t getonefromlist() { list<t> list = getmagicables(); //..... }
in case have compilation error in getmagicables() call:
type mismatch: cannot convert list<capture#2-of ? extends magicable> list<t>
third case causes compilation errors in both abovementioned places of code. don't think if solution in case.
- first case
just declare method with:
@override protected <t extends magicable> list<t> getmagicables() { list<t> list = ... return list }
if want this:
@override protected list<magican> getmagicable() {..}
you may have declare generic t class defintion
public abstract class abstractklass<t extends magicable> { protected abstract list<t> getmagicables(); }
then in subclass:
public class mysubclass extends abstractklass<magican> { @override protected list<magican> getmagicables() { ... } }
- second case
the compilation error normal because <? extends magicable>
signature of method means don't care what's inside list moment can consider elements magicable. when doing call
list<t> list = getmagicables();
you want take care of type t without knowing it. in other terms, there 3 use cases: t magicable (ok), t magician (wrong because getmagicables may return list of witch) , t witch (wrong too).
- why use
? extends magicable
instead ofmagicable
in lists
because list<magician>
subtype of list<? extends magicable>
not subtype of list<magicable>
. usefull parameters of methods.
public void doit(list<? extends magicable> list) { // can't add magician here }
may used
list<witch> list = ... doit(list);
but if have
public void doit(list<magicable> list) { // can add magician here }
you can't use
list<witch> list = ... doit(list); // compile error
Comments
Post a Comment