What type of parameter does the System.out.println()
method expect?
It expects a reference to a String as a parameter.
toString()
It looks like the following will not work:
Point a = new Point(); // a is a Point reference
System.out.println( a );
|
+--- should be String reference
However, it does work, for the following reason:
When a parameter should be aString
reference, but is a reference to another type of object, Java calls the object'stoString()
method to create aString
and then uses the resultingString
reference.
All objects (of any type at all) have their own toString()
method,
so this trick works with any object.
(Puzzle: ) Does a String
object have a toString()
method?