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:
uses string concatenation, which is specified in section 15.18.1 of the JLS, starting with:
Section 5.1.11 has:
This is just a language feature which is available for free. See Concatenating strings section:
You're calling
"p is " + p
, which effectively is compiled toThis code calls
p.toString()
within.append()
asp
isObject
.