// Helene Martin, CSE 142 // Point objects have x and y fields that represent // positions in 2D space. // demonstrates overwriting the equals method. public class Point implements Comparable { private int x; private int y; // Create a Point a the given position. public Point(int initialX, int initialY) { x = initialX; y = initialY; } // Create a Point representing the origin. public Point() { x = 0; y = 0; } // setters public void setX(int newX) { if (newX > 0) { x = newX; } } // Moves x and y coordinates of this point by specified amounts public void translate(int dx, int dy) { x += dx; y += dy; } // Changes the location of this Point. public void setLocation(int newX, int newY) { x = newX; y = newY; } // Returns this point's x coordinate. public int getX() { return x; } // Returns this point's y coordinate. public int getY() { return y; } // Returns the distance of this Point from the origin. public double distanceFromOrigin() { return Math.sqrt(x * x + y * y); } // Returns the distance between this Point and another Point. public double distance(Point other) { int dx = x - other.x; int dy = y - other.y; return Math.sqrt(dx * dx + dy * dy); } // Compares this Point to an other Point based first on their x coordinates // and then on their y coordinates public int compareTo(Point other) { if (x != other.x) { return x - other.x; } else { return y - other.y; // break ties in x } } // Returns this Point's coordinates surrounded by parentheses // and separated by a comma. public String toString() { return "(" + x + ", " + y + ")"; } // Returns true if this Point has the same coordinates as the other point public boolean equals(Object o) { if (o instanceof Point) { Point other = (Point) o; // need to cast o to have access to Point state/behavior return other.x == x && other.y == y; } else { // not the same type, can't be equal return false; } } }