I wonder why this is legal:
Object mystring = "hello";
System.out.println(mystring);
This prints hello
. But why Object
is treated like a string ?
I wonder why this is legal:
Object mystring = "hello";
System.out.println(mystring);
This prints hello
. But why Object
is treated like a string ?
Because a String
IS-A Object
, so a reference type can be any super types.
For instance, you could also assign mystring
to a CharSequence
type.
The println
method of PrintStream
(your System.out
static field) has an overload to take String
as an argument, and print it properly.
In this case though, the code in PrintStream#println(Object)
will actually print String.valueOf(x)
, where x
is your given argument.
It calls it's toString() method. The one that is implemented in the String class. Methods are binded at runtime.