Search code examples
javagenericsinheritancetypesabstract-class

java generics: Bound mismatch for string


my code is as below, and I got the error message Bound Mismatch Error: The type String is not a valid substitute for the bounded parameter <K extends myComparable<K>> of the type myInterface<K,V>:

interface myComparable<T> {
    public int compareTo(T o);
}

interface myInterface<K extends myComparable<K>, V> {  
}

public class myClass implements myInterface<String,String>{          
    public static void main(String[] args) {
    System.out.println("Hello world!");
    }    
}

However, if I changed K extends myComparable<K> to K extends Comparable<K> (without changing the first line; i.e. to use Comparable instead of myComparable), the error will be solved.

Why? And how can I use my own myComparable?


Solution

  • I finally got a solution (i.e. to use myString instead of String):

    interface myComparable<T> {
        public int compareTo(T o);
    }
    
    interface myInterface<K extends myComparable<K>, V> {
    }
    
    class myString implements myComparable<myString>{
        @Override
        public int compareTo(myString o) {
            return 0;
        }   
    }
    
    public class myClass implements myInterface<myString,myString>{      
        public static void main(String[] args) {
        System.out.println("Hello world!");
        }
    }