简体   繁体   中英

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

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>> <T extends Comparable<? super T>> . whats the difference ?

Thanks.

[Edited] - A passage from book Image

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>> <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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM