// Marty Stepp, CSE 142, Autumn 2009 // This file defines a new type of objects named Point. // // This third version of the class adds constructors, a toString method, // and encapsulation (private data fields). import java.awt.*; // for Graphics public class Point { // private fields (cannot be directly accessed outside this file) private int x; // each Point object has an int x and y in it private int y; // constructor (initializes the state of a newly created Point object) public Point(int initialX, int initialY) { // setLocation(initialX, initialY); x = initialX; y = initialY; } // Creates a new Point at location (0, 0). public Point() { // setLocation(0, 0); x = 0; y = 0; } // Returns the distance between this point and the given other point p2. public double distance(Point p2) { // "I'm a Point object." // "The client is asking me how far away I am from p2." int dx = x - p2.x; int dy = y - p2.y; double dist = Math.sqrt(dx*dx + dy*dy); return dist; } // Draws this point onto the given drawing window. public void draw(Graphics g) { g.fillOval(x, y, 3, 3); g.drawString(toString(), x, y); } // Modifies this point to have the given x/y coordinates. public void setLocation(int theX, int theY) { x = theX; y = theY; } // Shifts this point object's x/y position by the given amounts. public void translate(int dx, int dy) { // x = x + dx; // y = y + dy; setLocation(x + dx, y + dy); // call setLocation on this Point object } // Returns a String representation of this Point object. // This method is called automatically when a Point is printed. public String toString() { return "(" + x + ", " + y + ")"; } }