Why can methods be called on java interface methods? [comparable]

In AP Computer Science class today, I have this Code:

Comparable x = 45;
    Comparable y = 56;
    System.out.println(x.compareTo(y));

This is effective It prints 1 (or - 1, which I forgot), but you can compare them

I understand that the interface variable refers to the object of the class implementing the interface, but what doesn't make sense to me is how to allocate an integer to the interface variable and then call a method on it In this case, what object is the CompareTo () method being called? Nothing!

Solution

This is called autoboxing, and your original int type is automatically wrapped into an integer instance, which is an object that implements the comparable interface

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>