// CSE 142, Autumn 2010, Marty Stepp // This class defines a new type of objects named Point. // Each Point object represents one (x, y) location. // Today's version adds a constructor and some new methods. import java.awt.*; // for Graphics public class Point { int x; // each Point object has its own copy int y; // of each of these variables (fields) // constructor - Initializes new objects as they are created. // Example call: Point p = new Point(3, 5); public Point(int startX, int startY) { x = startX; y = startY; } // Returns the distance between this point and the origin, (0, 0). // Example call: p1.distanceFromOrigin() public double distanceFromOrigin() { return Math.sqrt(x*x + y*y); } // Returns the distance between this point and the given other point. // Example call: p1.distance(p2) // We pass just 1 point parameter, not 2, because the other point // is "this" point, the implicit parameter, the object you called the method on. public double distance(Point other) { int dx = other.x - x; int dy = other.y - y; return Math.sqrt(dx*dx + dy*dy); } // EACH Point object gets its own copy of the method, // the method knows which object you called it on, // and it can directly access the data (fields) in that object by name. // This method draws this point using the given graphics pen. public void draw(Graphics g) { g.fillOval(x, y, 3, 3); g.drawString("(" + x + ", " + y + ")", x, y); } // This method returns a String representation of this point, // such as "(3, -4)", so that Points can be printed. public String toString() { return "(" + x + ", " + y + ")"; } }