Alex Ozer
Alex Ozer

Reputation: 459

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!

Upvotes: 6

Views: 108

Answers (2)

Brian Agnew
Brian Agnew

Reputation: 272377

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.

Upvotes: 5

Jack
Jack

Reputation: 133619

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.

Upvotes: 11

Related Questions