0

When we need a String representation of an object, we can override the toString() method. However, what are the real benefits and reasons for overriding toString() when we can just define a new method to return the string?

Please see example below:

class One
{
    private String name;
    public One(String _name)
    {
        name = _name;
    }

    @Override public String toString()
    {
        return name;
    }       
}

class Two
{
    private String name;
    public Two(String _name)
    {
        name = _name;
    }

    public String printMyClass() //Self-defined to print class details
    {
        return name;
    }       
}

In the above example, printMyClass() which is self-defined seemed to does the same thing as toString().

So my question is: Why do we still use toString() ?

user3437460
  • 17,253
  • 15
  • 58
  • 106
  • 1
    For continuity. Example - when a developer needs to get a String representation of your object, then the first thing he uses is the toString(). – Reins Jul 22 '14 at 20:59
  • Also, if I recall correctly, if you print an object directly in Java (ie. `System.out.println(myObject);` ) it would call your toString() method rather than printing HashCode. I could be wrong. – Ricky Mutschlechner Jul 22 '14 at 21:01
  • 1
    Btw, I have a loose policy of "toString() for human-readable representation, another method for machine-parseable." So I may have for instance a `toString()` that I intend to read in a debugger, and a `toJsonString()` for when I want to serialize it (well, in real life I'd probably use jackson or some other library to json-ify it for me, but you get the point). – yshavit Jul 22 '14 at 21:02
  • @JoshuaTaylor It is a different question, because I am asking on the basis of comparing it with a self-defined method to return the string. – user3437460 Jul 22 '14 at 21:03
  • user3437460, yes, and if your reason for defining some other method that returns a string isn't the same reason for the toString method, then you're probably justified in writing a new method (e.g., @yshavit's toJsonString() method), but if it is the same reason, then you should just override Object#toString(). – Joshua Taylor Jul 22 '14 at 21:07

3 Answers3

5

The main benefits are that libraries expect this behaviour and use it.

If for example you log "funcX called with ("+param1+", "+param2+")" then toString() will automatically be called for you.

Additionally this means that you always know that the toString() method is available (since it is defined in so you can call it on every object without needing to worry about whether it is present or not.

A better question for you is why not use it? It's provided for you so why do you not want to use it?

Tim B
  • 40,716
  • 16
  • 83
  • 128
3

Easy conversion to String type that is used in String concatenation with + operator.

The benefit is that you don't have to write printMyClass() multiple times.

This is shorter

obj1 + " " + obj2

than this

obj1.printMyClass() + " " + obj2.printMyClass()

I do sometimes use it to help debugger show more readable output, but that's a little eccentric.

Grzegorz Żur
  • 47,257
  • 14
  • 109
  • 105
  • Is that the only benefit from technical point of view (meaning that I am not looking at "having it as a good practice..etc")? Thanks for answering! – user3437460 Jul 22 '14 at 21:01
  • Thanks for explanation. I got it now. Do you mind showing an example of using String concatenation with + operator on toString() ? Is this what you guys mean ? --> System.out.println(obj1 + obj2); – user3437460 Jul 22 '14 at 21:18
  • Ah, as I suspected, it needs to be concatenated with a String and cannot be concatenated by obj1 + obj2. +1 from me. Thanks for your reply. – user3437460 Jul 23 '14 at 08:52
1

Because toString is used by all other Java code to get a String representation of the Object.

Consider, for example, parametrised logging in SLF4j, here we use a format String and arguments to create a logging statement:

log.info("User {} has just logged in.", user);

The logging library will, if the logging level is low enough, take the format String and call toString on user in order to get the final logging message.

This is just one example of something that can generally be called a "call back". Since toString is part of the Java API many libraries use it to convert an Object to String. Doing the same, for example, deferred evaluation logging, would have required aninterface` and an anonymous class (pre Java 8) which is very messy.

In the most simple example consider String concatenation and implicit String conversion:

final String string = "User is " + user;

Without the toString method how would this even be possible?

Boris the Spider
  • 59,842
  • 6
  • 106
  • 166