String Conversion and toString( )

The toString( ) method has this general form:


String toString( )

By overriding toString( ) for classes that you create, you allow them to be fully integrated into Java's programming environment.

The System.out.println() calls the toString method from Rectangle to get the string representation of the rectangle instance.

 
class Rectangle {
  double width;
  double height;

  Rectangle(double w, double h) {
    width = w;
    height = h;
  }
  public String toString() {
    return "Dimensions are " + width + " by " + height + ".";
  }
}

public class Main {

  public static void main(String args[]) {
    Rectangle b = new Rectangle(10, 12);
    String s = "Rectangle b: " + b; // concatenate Rectangle object

    System.out.println(b); // convert Rectangle to string
    System.out.println(s);
  }
}

The output of this program is shown here:


Dimensions are 10.0 by 12.0.
Rectangle b: Dimensions are 10.0 by 12.0.
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.