tostring() is implicitly called… how?

前端 未结 3 1968
囚心锁ツ
囚心锁ツ 2021-01-17 04:59

In the following code, how is toString() is implicitly called?

class Payload {
    private int weight;
    public Payload (int w) {
        weig         


        
相关标签:
3条回答
  • 2021-01-17 05:36

    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)

    0 讨论(0)
  • 2021-01-17 05:38

    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.

    0 讨论(0)
  • 2021-01-17 05:46

    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.

    0 讨论(0)
提交回复
热议问题