/* * * a data structure that represents a 2d point * */ class Point { private double x; private double y; // method: two-argument constructor // in: doubles x and y // out: a new Point public Point(double x_in, double y_in) { this.x = x_in; this.y = y_in; } // method: zero-argument constructor // in: no inputs // out: a new Point (at the origin) public Point() // a zero-input constructor! { this.x = 0.0; this.y = 0.0; } // method: equals // in: a Point, p // out: a boolean, whether or not this and p are the same Point public boolean equals(Point p) { if (this.x == p.x && this.y == p.y) return true; else return false; } // method: toString // in: none // out: a String representation of this Point public String toString() { String s = "(" + this.x + "," + this.y + ")"; return s; } // method: add // in: a Point, p // out: a new Point that is the sum of this and p public Point add(Point p) { return new Point(this.x + p.x, this.y + p.y); } // method: scale // in: a double, d, the factor by which to scale // out: a new Point that is a scaled version of this public Point scale(double d) { return new Point(d * this.x, d * this.y); } // method: isSmaller // in: a Point, p // out: whether or not this is closer to the origin than p public boolean isSmaller(Point p) { // could be more concise, but it's not bad to // see how to call Math functions // the Java API lists them all (Google for "Java 1.6 API") double magThis = Math.sqrt(this.x * this.x + this.y * this.y); double magOfp = Math.sqrt(p.x * p.x + p.y * p.y); return (magThis < magOfp); } // method: main // in: usual stuff, ignored as usual // out: nothing (a void function) // ** printing stuff is quite different from returning stuff! ** public static void main(String[] args) { Point p1 = new Point(30, 40); Point p2 = new Point(12, 2); Point p3 = p1.add(p2); System.out.println("p1 is " + p1); System.out.println("p2 is " + p2); System.out.println("p3 (sum) is " + p3); Point p4 = p1.scale(0.5); System.out.println("p4 is " + p4); if (p2.isSmaller(p1)) { System.out.println("p2 IS smaller than p1."); } else { System.out.println("p2 is NOT smaller than p1!"); } } }