Try this code
Object x = 1;
String y = "";
x += y; //compile error
x = x + y; //works properly
not entirely sure why this works, but the compiler says
The operator += is undefined for the argument type(s) Object, String
and I assume that for the second line, toString
is called on the Object.
EDIT:
It makes sense as the +=
operator is meaningless on a general Object. In my example I cast an int to an Object, but it only depends on x
being of type Object:
Object x = new Object();
It only works if x
is Object though, so I actually think it is more that String is a direct subclass of Object. This will fail for x + y
:
Foo x = new Foo();
for other types that I have tried.