// CSE 142, Summer 2008 (Marty Stepp) // This file defines a new type of objects named Point. // // Today's version has the following new features: // - more methods (distance, distanceFromOrigin, ...) // - a constructor, so we can say new Point(3, 5) // - a toString method, so that we can println Points // - encapsulation (private fields), so other classes // can't directly change a Point's x or y value public class Point { // Fields: // What contents should each Point object have? private int x; private int y; // EACH Point object has an int x and int y inside it. // Constructor: // How is each Point object initialized? public Point(int initialX, int initialY) { x = initialX; y = initialY; } // Methods: // What behavior should each Point object have? // Shifts the x/y position of this Point by the given amounts. public void translate(int dx, int dy) { setX(x + dx); setY(y + dy); } // Returns the direct distance between this Point and the origin, (0, 0). public double distanceFromOrigin() { // square root of (a^2 + b^2) return Math.sqrt(x*x + y*y); } // Returns the direct distance between this Point and the given other Point. public double distance(Point otherPoint) { int a = otherPoint.x - x; // change in x int b = otherPoint.y - y; // change in y return Math.sqrt(a*a + b*b); } // Converts this Point's state into a String and returns that String. public String toString() { return "(" + x + ", " + y + ")"; } // 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 coordinate to the given value. // Does not allow negative values. public void setX(int value) { x = Math.max(0, value); } // Sets this Point's y coordinate to the given value. // Does not allow negative values. public void setY(int value) { y = Math.max(0, value); } }