tostring() is implicitly called… how?

2019-02-21 05:57发布

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);
    }
}

3条回答
够拽才男人
2楼-- · 2019-02-21 06:47

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 the toString method is null, then the string "null" is used instead.

查看更多
手持菜刀,她持情操
3楼-- · 2019-02-21 06:49

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.

查看更多
Viruses.
4楼-- · 2019-02-21 06:53

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)

查看更多
登录 后发表回答