Java - Reimplementing toString() Method of the Object Class in the Point Class

Requirement

  • Suppose you have a Point class to represent a 2D point.
  • A Point holds the x and y coordinates of a point.
  • An implementation of the toString() method in the Point class may return a string of the form (x, y), where x and y are the coordinates of the point.

Demo

class Point {
  private int x;
  private int y;

  public Point(int x, int y) {
    this.x = x;/*from w  w  w  .  j a  v a  2 s .c  om*/
    this.y = y;
  }

  /* Reimplement toString() method of the Object class */
  public String toString() {
    String str = "(" + x + ", " + y + ")";
    return str;
  }
}

public class Main {
  public static void main(String[] args) {

    Point pt = new Point(10, 12);

    String str1 = "Test " + pt;
    String str2 = "Test " + pt.toString();

    // str1 and str 2 will have the same content
    System.out.println(pt);
    System.out.println(pt.toString());
    System.out.println(str1);
    System.out.println(str2);

    pt = null;
    String str3 = "Test " + pt;
    System.out.println(pt);
    System.out.println(str3);

  }
}

Result

Related Topic