Java – toString: when to use?
I'm in class
class Configuration { // varIoUs stuff @Override public String toString() { // assemble outString return outString; } }
I have another class
class Log { public static void d(String format,Object... d) { // print the format using d } }
The log class works very well. I've been using it all the time Now when I do this:
Configuration config = getConfiguration(); Log.d(config);
I got a compiler error. The method D (string, object...) in the log type is not applicable to the parameter (configuration) I can solve this problem:
Log.d("" + config); // solution 1 Log.d(config.toString()); // solution 2
My question: what's the difference? In the first solution, the compiler notes that it must connect two strings, but the second is configuration So configuration #tostring() is called and everything is fine In the case of compiler error, the compiler found that a string was required, but gave a configuration It's basically the same problem
>Required: String > View: Configuration
How are these cases different and why are there no call strings?
Solution
When designing the language, it was decided that when programmers use operators to attach arbitrary objects to strings, they must need a string, so it makes sense to call toString () implicitly
But if you call any method of a string with something else, it's just a type error, which all static types should prevent