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.
You're calling "p is " + p
, which effectively is compiled to
new StringBuffer("p is").append(p)
This code calls p.toString()
within .append()
as p
is Object
.
Specified by:
http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html#append(java.lang.Object)
This is just a language feature which is available for free. See Concatenating strings section:
Such a concatenation can be a mixture of any objects. For each object that is not a String, its toString() method is called to convert it to a String.
来源:https://stackoverflow.com/questions/24720321/tostring-is-implicitly-called-how