package eecs2030.lectures; import java.util.Objects; /** * A simple class for representing points in 2D Cartesian coordinates. Every * SimplePoint2D instance has a public x and y coordinate that can * be directly accessed and modified. * * @author EECS2030 Fall 2017-18 * */ public class SimplePoint2 { public float x; public float y; /** * The default constructor. Sets both the x and y coordinate of this point * to 0.0f. */ public SimplePoint2() { this(0.0f, 0.0f); } /** * Sets the x and y coordinate of this point to the argument values. * * @param x * the x coordinate of the point * @param y * the y coordinate of the point */ public SimplePoint2(float x, float y) { this.x = x; this.y = y; } /** * Sets the x and y coordinate of this point by copying the x and y * coordinate of another point. * * @param other * a point to copy */ public SimplePoint2(SimplePoint2 other) { this(other.x, other.y); } /** * Sets the x and y coordinate of this point to the argument values. * * @param x * the new x coordinate of the point * @param y * the new y coordinate of the point */ public void set(float x, float y) { this.x = x; this.y = y; } /** * Returns a hash code for this point. * * @returns a hash code for this point */ @Override public int hashCode() { return Objects.hash(this.x, this.y); } /** * Compares this point to the specified object. The result is true if and * only if the argument is not null and is a SimplePoint2 object that has * the same coordinates as this point. * * @param obj * the object to compare this SimplePoint2 against * @returns true if the given object represents a SimplePoint2 equivalent to * this point, and false otherwise */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } SimplePoint2 other = (SimplePoint2) obj; if (Float.floatToIntBits(x) != Float.floatToIntBits(other.x)) { return false; } if (Float.floatToIntBits(y) != Float.floatToIntBits(other.y)) { return false; } return true; } /** * This is the original version of the main method from the lecture * slides that does not use the custom constructor, copy constructor, * nor any methods of SimplePoint2. * * @param args not used */ public static void main(String[] args) { // create a point SimplePoint2 p = new SimplePoint2(); // set its coordinates p.x = -1.0f; p.y = 1.5f; // get its coordinates System.out.println("p = (" + p.x + ", " + p.y + ")"); System.out.println("p = " + p.toString()); SimplePoint2 q = new SimplePoint2(); q.x = p.x; q.y = p.y; // equals? System.out.println("p.equals(q) is: " + p.equals(q)); } }