// A Point object represents a pair of (x, y) coordinates. // Fifth version: encapsulated, with state, behavior, and constructor, // and with toString method and this keyword. public class Point { // fields (the state of each Point object) private int x; private int y; // Constructs a new Point object at the origin, (0, 0). public Point() { // using the this keyword to call one constructor from another this(0, 0); } // Constructs a new Point object with the given initial location. public Point(int x, int y) { setLocation(x, y); } // Returns the distance between this point and the given other point. public double distance(Point other) { int dx = x - other.x; int dy = y - other.y; return Math.sqrt(dx * dx + dy * dy); } // Returns the distance between this point and (0, 0). public double distanceFromOrigin() { return distance(new Point(0, 0)); } // Returns this Point's x-coordinate. public int getX() { return x; } // Returns this Point's y-coordinate. public int getY() { return y; } // Sets this Point's (x, y) to the given location. public void setLocation(int x, int y) { if (x < 0 || y < 0) { throw new IllegalArgumentException(); } // using the this keyword to avoid shadowing (so the parameters // can have the same names as their corresponding fields) this.x = x; this.y = y; } // Returns a text representation of this Point object. public String toString() { return "(" + x + ", " + y + ")"; } // Shifts this point's location by the given amounts. public void translate(int dx, int dy) { setLocation(x + dx, y + dy); } }