2

suppose we have

class Fruit implements Comparable<Fruit>
{
    @Override
    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 ?

Thanks.

[Edited] - A passage from book Image

belnxkkk
  • 335
  • 2
  • 11

2 Answers2

0

In this case it is beacuse class Fruit is a superclass of itself

The difference is here

<T extends Comparable<T>> accepts Comparable with arguement of type T <T extends Comparable<? super T>> accepts Comparable with arguements of type T and its super classes. Here Since in java every class is a superclass of itself, Fruit is also a superclass of Fruit .Thats why you see like they are working the same way But if you used class Apple as T you will see the difference.

henrybbosa
  • 1,083
  • 10
  • 27
0

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" ?

davidxxx
  • 104,693
  • 13
  • 159
  • 179