Unlimited wildcards with extensions and super like options

Help me figure out why I can't call the testSuper () method? Compilation Error:

The method testSuper(Group<? super BClass<?>>) in the type Group <BClass<String>> is not applicable for the arguments (Group<AClass<String>>) 

But the testExtends () method is fine. However, it looks the same.

 class AClass<T> {} class BClass<T> extends AClass<T> {} class Group<T> { T name; public void testExtends(Group<? extends AClass<?>> value){} public void testSuper(Group<? super BClass<?>> value){} public T getName(){return name;} } public class GenericTest { public static void GenericTestMethod(){ Group<AClass<String>> instGrA = new Group<AClass<String>>(); Group<BClass<String>> instGrB = new Group<BClass<String>>(); //OK instGrA.testExtends(instGrB); //The method testSuper(Group<? super BClass<?>>) in the type Group <BClass<String>> //is not applicable for the arguments (Group<AClass<String>>) instGrB.testSuper(instGrA); } } 
+5
source share
1 answer

There is a difference between the challenges.

In a query that compiles,

 instGrA.testExtends(instGrB); 

are you passing Group<BClass<String>> method waiting for Group<? extends AClass<?>> Group<? extends AClass<?>> . This is appropriate because BClass<String> is a subtype of AClass<?>> - BClass is a subclass of AClass and String is a subtype ? .

However, in a call that does not compile,

 instGrB.testSuper(instGrA); 

are you passing Group<AClass<String>> method waiting for Group<? super BClass<?>> Group<? super BClass<?>> . This is not appropriate because, although AClass is a superclass of BClass , AClass<String> not a supertype of BClass<?> .

The wildcards inside the testExtends and testSuper parameters testExtends testSuper . Since you assign AClass and BClass to T in your instances, you can use them. I can get this to compile if we change the declarations of these methods in Group to use T :

 public void testExtends(Group<? extends T> value){} public void testSuper(Group<? super T> value){} 
+3
source

Source: https://habr.com/ru/post/1242047/


All Articles