// A Point object represents a pair of (x, y) coordinates. // Fourth version: encapsulated, with state, behavior, and constructor. // Class invariant: x >= 0 && y >= 0 for all Points at all times. 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() { setLocation(0, 0); } // Constructs a new Point object with the given initial location. public Point(int initialX, int initialY) { setLocation(initialX, initialY); } // 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 newX, int newY) { if (newX < 0 || newY < 0) { throw new IllegalArgumentException(); } x = newX; y = newY; } // Shifts this point's location by the given amounts. public void translate(int dx, int dy) { setLocation(x + dx, y + dy); } }