This content has been marked as final. Show 5 replies
jose_an wrote:println(X) ends up calling X.toString(). Since "hello" is a String, not a BobTest, it's String's implementation of toString() that get's called. Not surprisingly, "hello".toString() gives "hello".
System.out.println(f); // if i put s.o.p("hello"); the overridden toString doesnt get called, y so ?
masijade. wrote:And just to further the point
To get a meaningful String representation of your Object.
@OP: In answer to your original question: almost always.
I generally don't regard a class as complete until I've implemented toString() -- or, at the very least, displayed it with println() and determined that the default representation is fine.
Same goes for equals() and hashCode().
1. When do you have to override toString(). Never.
2. When/why would you want to? It makes your life infinitely easier when you can quickly dump object contents to a debug console, log, etc. For that reason, many consider it best practice to include a toString() override in virtually every class. And programmers who have to maintain your code will be eternally grateful