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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With