javagenerics

Why this generic reference can't point to this similar extended class in Java?


Why this generic reference can't point to this similar extended class in Java?

public class HelloWorld{

    public static void main(String []args){
 
        Interface<Integer,Object> test = new Test();
 
        System.out.println(test.method(test));
    }
}


public interface Interface<A, B extends Object> {
    public A method(B param);
}

public class Test implements Interface<Integer,Test> {
    private int a = 0;

    public Integer method(Test param){
        return param.a;
    }
}

I get this error when compiling

HelloWorld.java:5: error: incompatible types                                                                                                                         
        Interface<Integer,Object> test = new Test();                                                                                                                 
                                         ^                                                                                                                           
  required: Interface<Integer,Object>                                                                                                                                
  found:    Test                                                                                                                                                     
1 error  

            

Solution

  • The class Test implements Interface<Integer,Test> and the type is declared as Interface<Integer,Object>. This assignment is not allowed because Generics are invariant:

    Interface<Integer,Test> is neither a subtype nor a supertype of Interface<Integer,Object>. So, Interface<Integer,Test> cannot be assigned to Interface<Integer,Object>.

    You can change the assignment statement as below to make it work :

    Interface<Integer, ? extends Test> test = new Test();