// Improved Point class: this object // now has constructors, a toString() // and a distanceFrom(Point other) method // // It's main remaining problem is that the // fields are open for clients to interact // with -- we should make them private // Note that since I called this version of the Point class // Point2, I had to rename the object everywhere: public class Point2 { // state // fields int x; int y; // No-parameter constructor that sets this // Point to be located at (0, 0) public Point2() { //x = 0; //y = 0; this(0, 0); } // constructor that allows client to set // x and y during object construction public Point2(int x, int y) { // set state to the values being passed // use this. to refer to this object's // fields, instead of the parameters this.x = x; this.y = y; } // Another way of solving the duplicate-name // problem: change the name of our parameters // so that we don't shadow the fields. //public Point2(int xLocation, int yLocation) { // x = xLocation; // y = yLocation; //} // behavior: instance methods that we can // call ON a specific Point object: // mutators: methods that change state // moves the move by the given deltaX and // deltaY public void translate(int dx, int dy) { x += dx; y += dy; } // accessors // returns distance from origin public double distanceFromOrigin() { return Math.sqrt(x * x + y * y); } // returns distance from given other Point public double distanceFrom(Point2 that) { int dx = this.x - that.x; int dy = this.y - that.y; return Math.sqrt(dx * dx + dy * dy); } // returns a String representation of this Point // "(x, y)" public String toString() { return "(" + x + ", " + y + ")"; // Default behavior of toString() // looks like this: //return "Point@" + getMemoryAddress(); } }