Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it possible to call method on Java interface method? [Comparable]

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

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

And this is valid. It prints 1 (or -1, I forget which), but it is possible to compare them.

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

like image 999
Alex Ozer Avatar asked Feb 20 '13 17:02

Alex Ozer


1 Answers

This is called autoboxing, your primitive int type is automatically wrapped into an Integer instance, which is an object and it does implement Comparable interface.

like image 116
Jack Avatar answered Nov 14 '22 21:11

Jack