In the following code, how is toString()
is implicitly called?
class Payload {
private int weight;
public Payload (int w) {
weight = w;
}
public void setWeight(int w) {
weight = w;
}
public String toString() {
return Integer.toString(weight);
}
}
public class testpayload {
static void changePayload(Payload p) {
p.setWeight(420);
}
public static void main(String[] args) {
Payload p = new Payload(200);
p.setWeight(1024);
changePayload(p);
System.out.println("p is " + p);
}
}
This line:
System.out.println("p is " + p);
uses string concatenation, which is specified in section 15.18.1 of the JLS, starting with:
If only one operand expression is of type String, then string conversion (ยง5.1.11) is performed on the other operand to produce a string at run time.
Section 5.1.11 has:
Any type may be converted to type
String
by string conversion....
Now only reference values need to be considered:
If the reference is
null
, it is converted to the string"null"
(four ASCII characters n, u, l, l).Otherwise, the conversion is performed as if by an invocation of the
toString
method of the referenced object with no arguments; but if the result of invoking thetoString
method isnull
, then the string"null"
is used instead.
See more on this question at Stackoverflow