// Represent a cartesian coordinate. class Point { int x; int y; Point(int x, int y) { this.x = x; this.y = y; } // calculate the distance from this point to given point. double distTo(Point that) { /* Template ... this.x ... int ... this.y ... int ... that.x ... int // Q: Are these warranted? ... that.y ... int */ return Math.sqrt((this.x - that.x) * (this.x - that.x) + (this.y - that.y) * (this.y - that.y)); } } /* +--------+ | IShape | +--------+ +--------+ | / \ --- | ------------------- | | +------------+ +------------+ | Circle | | Rectangle | +------------+ +------------+ | Point loc | | Point loc | // Center, NW corner, resp. | int radius | | int height | +------------+ | int width | +------------+ */ // Represent shapes interface IShape { // does this shape contain the given point? boolean contains(Point p); } // Represent a circle class Circle implements IShape { Point loc; int radius; Circle(Point loc, int radius) { this.loc = loc; this.radius = radius; } // does this circle contain the given point? boolean contains(Point p) { /* Template ... this.loc ... Point ... this.radius ... int ... p ... Point // Q: Should we add p.x, p.y here? */ return p.distTo(this.loc) <= this.radius; } } // Represent a rectangle class Rectangle implements IShape { Point loc; int height; int width; Rectangle(Point loc, int height, int width) { this.loc = loc; this.height = height; this.width = width; } // does this rectangle contain the given point? boolean contains(Point p) { /* Template ... this.loc ... Point ... this.height ... int ... this.width ... int ... p ... Point */ return this.between(this.loc.x, p.x, this.width) && this.between(this.loc.y, p.y, this.height); } // is x in the interval [lft, lft+width]? boolean between(int lft, int x, int width) { return lft <= x && x <= lft + width; } } class ShapeExamples { ShapeExamples () {} IShape circ = new Circle(new Point(10,10),5); IShape rect = new Rectangle(new Point(10,15),10,20); Point pout = new Point(0,0); // in neither. Point pincirc = new Point(8,12); // in circle, not rect. Point pinrect = new Point(18,18); // in rect, not circle. Point p = new Point(3,4); boolean distToTests = check this.p.distTo(this.pout) expect 5.0 within 0.00001; boolean containsTests = ((check this.circ.contains(this.pout) expect false) && (check this.circ.contains(this.pinrect) expect false) && (check this.circ.contains(this.pincirc) expect true) && (check this.rect.contains(this.pout) expect false) && (check this.rect.contains(this.pinrect) expect true) && (check this.rect.contains(this.pincirc) expect false)); }