// This class defines a blueprint for PositivePoint objects. // PositivePoint have an x and y value that are never negative. // // If something happens that would set the x or y value to a // negative number, it gets set to 0 instead. // // PositivePoints have methods for translating, finding the // distance to the origin and converting to Strings. public class PositivePoint { //fields: data / information // These fields are private so that no client can change them directly private int x; private int y; //Constructors: public PositivePoint(int x, int y){ //since the arguments and fields have the same name, Java could // get confused, so "x" refers to the argument and "this.x" refers // to the field. this.x = x; this.y = y; // fix x and y if either were set to a negative value guaranteePositive(); } public PositivePoint(){ this.x = 0; this.y = 0; } //instance methods: behavoir / actions // Translates this point by the given dx and dy public void translate(int dx, int dy) { this.x += dx; this.y += dy; // fix x and y if either were set to a negative value guaranteePositive(); } // Returns this Point's distance from origin public double distanceFromOrigin() { return Math.sqrt(x * x + y * y); } // Returns the String representation of this Point. public String toString(){ return this.x + ", " + this.y; } // This is an internal helper method to make sure the x and y values // never end up negative. // It labeled "private" since no one outside the object needs it, but // it would still work if it were labeled "public". private void guaranteePositive(){ if(this.x < 0) { this.x = 0; } if(this.y < 0) { this.y = 0; } } }