// 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 encapsulation, // which means that the fields are private so the client can't mess with them. import java.awt.*; // for Graphics public class Point { private int x; // each Point object has its own copy private int y; // of each of these variables (fields) // Constructs a point at the given x/y coordinates. // A constructor gets called when client asks for a 'new' object // A constructor's duty is to initialize the state of that new object. public Point(int initialX, int initialY) { x = initialX; y = initialY; } // Constructs a point at the origin, (0, 0). public Point() { // don't need to set them to 0 because they already start out as 0 // x = 0; // y = 0; } // Returns the x-coordinate of the point. public int getX() { return x; } // Returns the x-coordinate of the point. public int getY() { return y; } // Shifts the position of the point by the given x/y amounts. public void translate(int dx, int dy) { x += dx; y += dy; } // 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 + ")"; } }