tostring() is implicitly called… how?

馋奶兔 提交于 2019-12-01 14:23:52

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!