toString:什么时候使用?

bri*_*ium 6 java tostring

我上课了

class Configuration {
  // various stuff

  @Override
  public String toString() {
    // assemble outString
    return outString;
  }
}
Run Code Online (Sandbox Code Playgroud)

我还有另一堂课

class Log {
  public static void d(String format, Object... d) {
    // print the format using d
  }
}
Run Code Online (Sandbox Code Playgroud)

Log类工作得非常好,我一直都在使用它.现在当我这样做:

Configuration config = getConfiguration();
Log.d(config);
Run Code Online (Sandbox Code Playgroud)

我得到编译器错误The method d(String, Object...) in the type Log is not applicable for the arguments (Configuration).我可以解决这个问题:

Log.d("" + config);       // solution 1
Log.d(config.toString()); // solution 2
Run Code Online (Sandbox Code Playgroud)

我的问题:这有什么不同?在第一个解决方案中,编译器注意到它必须连接两个字符串,但第二个是配置.所以Configuration#toString()被称为一切都很好.在编译器错误情况下,编译器发现需要一个String,但是给出了一个Configuration.基本上是同样的问题.

  • 需要:字符串
  • 鉴于:配置

这些案件有何不同,为什么toString不被称为?

Mic*_*rdt 11

在设计语言时,有人决定当程序员使用+运算符将任意对象附加到字符串时,他们肯定想要一个String,所以隐式调用toString()是有道理的.

但是如果你调用一个String带有其他东西的任意方法,那只是一个类型错误,正是所有静态类型应该阻止的.