// Marty Stepp, CSE 142, Autumn 2009 // This file defines a new type of objects named Point. // // This second version of the class adds methods to each object. // // Keep in mind that each method's code is copied into each Point, // and the code runs inside that Point object. // Think of the method as having an identity; it knows which object // it was called on and can access that object's x/y fields directly. import java.awt.*; // for Graphics public class Point { int x; // each Point object has an int x and y in it int y; // Draws this point onto the given drawing window. public void draw(Graphics g) { g.fillOval(x, y, 3, 3); g.drawString("(" + x + ", " + y + ")", x, y); } // 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; } // 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 } }