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

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

Posted by: admin December 28, 2021 Leave a comment

Questions:

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!

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.

###

Your integers are being boxed to Integers (i.e. Objects). That is to say, the primitives are being replaced by objects wrapping those primitives. Note that Integer implements Comparable.