Hi I would be really interested to understand how exactly the toString() method works. I have read quite a bit about it, that it returns the string representation of
an object, that the default one can be overridden with @Override etc etc.
Let's have a look at some examples:

   @Override // indicates that this method overrides a superclass method
   public String toString()
   {
      return String.format( "%s: %s %s\n%s: %s\n%s: %.2f\n%s: %.2f", 
         "commission employee", firstName, lastName, 
         "social security number", socialSecurityNumber, 
         "gross sales", grossSales, 
         "commission rate", commissionRate );
   } // end method toString

and it is called in this way

System.out.printf( "\n%s:\n\n%s\n", 
         "Updated employee information obtained by toString", 
         employee.toString() );

where employee is an object. firstName, lastName etc are all private instance variables of the class

Or anothe similar one:

@Override // indicates that this method overrides a superclass method
   public String toString()
   {
      return String.format( "%s: %s %s\n%s: %s\n%s: %.2f\n%s: %.2f", 
         "commission employee", firstName, lastName, 
         "social security number", socialSecurityNumber, 
         "gross sales", grossSales, 
         "commission rate", commissionRate );
   } // end method toString

which is called by

 System.out.printf( "\n%s:\n\n%s\n", 
         "Updated employee information obtained by toString", employee );

again, employee is the object.

Now what I don't understand is what is the difference between printing an object this way and printing an object with a normal call to System.out.printf and list the instance
variables? I mean why do I need a toString method for? Maybe in the examples above, since they are taken from large program, I might not see the point of it.

Recommended Answers

All 5 Replies

You normally don't have access to the instance variables of an object. If you want encapsulation, you need to make your fields private, and that means you can't call printf with the instance variables from anywhere outside of the class.

On the other hand, it is good practice to make all the information returned by toString also available directly so that no one ever needs to parse the string. If you use only classes that follow that practice, then you will always be able to avoid toString as you suggest.

I'm sure you don't actually want to type out long and potentially very complicated sequences of printf calls just to avoid calling toString, but the answer to your question is that usually you can do it if you are willing to waste your time and the time of everyone who ever reads your source code. There is no real difference.

It's just a convenience thing. It means you can print anything simply like

Object something = ...         // can be absolutely anything
System.out.print(something);   // will always work because print actually calls something.toString()

and it will always work and usually tell you enough to identify what something was.

you don't need to add the @Override annotation in order to actually override the method.

the Object class contains a toString method as base funcionality, so each and every class have a toString method (even if it's just the one they inherit from Object).

actually, when you perform something like:

MyObject ob = new MyObject();
System.out.println(ob);

if you were wondering what the println() command is actually doing: it is printing the value that is returned by the toString method in your console.

if you didn't override the toString method, it would print something like this:

MyObject@3e25a5

now ... if MyObject would be a person, with two instance variables: name and firstName, and you would want to print these, you would have to add something like this:

@Override
public String toString(){
    return this.firstName + " " + this.lastName;
}

you don't need to add the @Override annotation in order to actually override the method.

... but it is a Very Good Thing To Do because it tells the compiler to check that you have correctly overidden a superclass method, thus avoiding annoying bugs like

public String toStrimg() {
  return this.firstName + " " + this.lastName; // doesn't get executed when you expect
}

Ok thanks, I think it is clear. Will see when I will use it : - )!
thanks for the explanations!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.