toString: When is it used?

Viewed 294

I have a class

class Configuration {
  // various stuff

  @Override
  public String toString() {
    // assemble outString
    return outString;
  }
}

I also have another class

class Log {
  public static void d(String format, Object... d) {
    // print the format using d
  }
}

The Log class works perfectly fine, I use it all the time. Now when I do this:

Configuration config = getConfiguration();
Log.d(config);

I get the compiler error The method d(String, Object...) in the type Log is not applicable for the arguments (Configuration). I can solve this:

Log.d("" + config);       // solution 1
Log.d(config.toString()); // solution 2

My problem: How is this different? In the first solution, the compiler notices that it has to concatenate two Strings, but the second one is a Configuration. So Configuration#toString() is called and everything is fine. In the compiler error case the compiler sees that a String is needed, but a Configuration is given. Basically the same problem.

  • Needed: String
  • Given: Configuration

How are these cases different and why is toString not called?

6 Answers
Related