8.4 The toString Method

When we pass a reference to object in System.out.println(), Java will call the object's toString() method. You can override toString() and provide your own string representations. The following program demonstrates this by overriding toString( ) for the Rectangle class:

Program (Rectangle.java)

/**
 * Rectangle class demonstrating toString method
 */
public class Rectangle
{
   private double length;
   private double width;

   /**
    *  Constructor
    */
   public Rectangle(double l, double w)
   {
      length = l;
      width  = w;
   }

   /**
    * The overriding toString method returns the
    * string containing object's length and width
    */
   public String toString()
   {
      return "Length : " + length + "\nWidth : " + width;
   }
}

Program (RectangleDemo. Java)

/**
 *   This program demonstrate Rectangle's
 *   class toString method.
 */
public class RectangleDemo
{
   public static void main(String[] args)
   {
      // Create a Rectangle object with given set of values
      Rectangle rect = new Rectangle(3.5, 4.2);

      // Display the object's values.Calling toString method implicitly
      System.out.println(rect);
   }
}          

Output :

Length : 3.5
Width : 4.2