Rules for toString() Methods

toString() methods should return a single line of text that does not contain any carriage returns or linefeeds.

toString() methods are primarily for debugging.

toString() should not do a lot of fancy processing. toString() methods should be quick.

The string returned by toString() should contain the name of the class, and names and values of the fields that represent the state of the object, unless there are an excessive number of such fields, in which case only the most important should be returned.

A better Car toString() method would be:

 public String toString() {
    return "[Car: plate=" + this.licensePlate 
     + "; speed=" + this.speed + "; MaxSpeed=" + this.maxSpeed +"]");
  }

These rules are conventions, not requirements of the language.


Previous | Next | Top | Cafe au Lait

Copyright 1997, 1998, 2006 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified February 6, 2006