Here I just create two simple class Dad and Son, Son is a subclass of Dad.
public class Dad {
}
public class Son extends Dad {
}
Then I create a Function in other class to test
public class Test {
public static void main(String[] args) {
Function<? extends Dad, String> fun = son -> son.toString();
fun.apply(new Son());
}
But I came across a compiler error on fun.apply(new Son()), it says 'apply (captrue in Funtion cannot be appiled to (Son))'. I am confused, the fun need a param of class which extends Dad, I give the subclass but is not right at all.
What's more! I try new Dad() as the param for the fun, but also got the error message 'apply (captrue in Funtion cannot be appiled to (Dad))'
Finally, I don't know which param can be used when the Function with generic version.
Help~~~ Thanks! (⊙o⊙)
extends Dadthen why can't you just useFunction<Dad,String>instead ofFunction<? extends Dad, String>?public enum EnumTest { SON1((Son1 son1) -> son1.getName()), SON2((Son2 son2) -> son2.getNickName()); private Function<? extends Dad, String> fun; EnumTest(Function<? extends Dad, String> fun) { this.fun = fun; } public Function<? extends Dad, String> getFun() { return fun; } }