toString() Methods

Print methods are common in some languages, but most Java programs operate differently. You can use System.out.println() to print any object. However for good results your class should have a toString() method that formats the object's data in a sensible way and returns a string. Otherwise all that's printed is the name of the class which is normally not what you want. For example, a good toString() method for the Car class might be

 public String toString() {
    return  (this.licensePlate + " is moving at " + this.speed 
     + "kph and has a maximum speed of " + this.maxSpeed +"kph.");
  }

Previous | Next | Top | Cafe au Lait

Copyright 1997, 1998 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified October 16, 1998