Why can I call a method on a Java interface method? [Comparable]

In the AP Computer Science class today, I had this code:

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

And it really is. It prints 1 (or -1, I forgot that), but they can be compared.

I understand that interface variables refer to an object of the class that implements this interface, but it makes no sense to me how an interface variable can be assigned an integer, and then the method called. What object is the compareTo () method called in this case? Nothing was even instantiated!

+6
source share
2 answers

This is called autoboxing , your primitive int type is automatically included in the Integer instance, which is an object and implements Comparable .

+11
source

Your integers are put into integers (i.e. Objects ). In other words, primitives are replaced with objects wrapping these primitives. Note that Integer implements Comparable .

+5
source

All Articles