Ibrahim Ibrahim - 1 year ago 74
Java Question

How come <T extends Comparable<T>> working as <T extends Comparable<? super T>>?

suppose we have

class Fruit implements Comparable<Fruit>
public int compareTo(Fruit o) { return 0; }

class Apple extends Fruit{}

class Main

public static void main (String args[])
function(new Apple()); // this shouldn't work because Apple is implementing Comparable<Fruit>, not Comparable<Apple>

public static<T extends Comparable<T>> void function(T t){}

Code is working without any issue.

My question is why
<T extends Comparable<T>>
working like
<T extends Comparable<? super T>>
. whats the difference ?


[Edited] - A passage from book

Answer Source

You compile with Java 8 I think. Because, before Java 8, you should not pass the compilation and have this error :

Bound mismatch: The generic method function(T) of type Main is not applicable for the arguments (Apple). The inferred type Apple is not a valid substitute for the bounded parameter >

I think what you read in your book refers to generic use before Java 8.
But i didn't know that Java 8 had less constraint on this kind of case.
Is it a side-effect of the large use of inference in Java 8 that Java 8 calls the "improved inference" ?