©2005 Felleisen, Proulx, et. al.
Methods and Unions of Classes
Figures 3.1 and 3.2 show a part of a class hierarchy for a family of shapes.
Construct examples of the Square class, and test cases for each method
declared in the abstract class.
Next, extend the hierachy to include the Circle
and
Dot
classes described in the textbook. Be sure to provide
examples of data and test cases for these functions too.
Draw a class diagram for the classes of problem 3.3.
// represents an abstract shape abstract class AShape { CartPt loc; // to compute the area of this shape abstract double area(); // to compute the distance of // this shape to the origin abstract double distTo0(); // is the given point within // the bounds of this shape abstract boolean in(CartPt p); // compute the bounding box // for this square abstract Square bb(); } | //represents a square (this.loc at top left) class Square extends AShape { int size; Square(CartPt loc, int size) { ... // omitted } double area() { return this.size * this.size; } double distTo0() { return this.loc.distTo0(); } boolean in(CartPt p){ return this.inRange(this.loc.y, p.y, this.size) && this.inRange(this.loc.x, p.x, this.size); } Square bb() { return this; } // is x in the interval [lft,lft+wdth]? boolean inRange(int lft, int x, int wdth) { return lft <= x && x <= lft + wdth; } } |
class CartPt { int x; int y; CartPt(int x, int y) { ... // omitted ... } // to compute the distance of this point to the origin double distTo0(){ return Math.sqrt( (this.x * this.x) + (this.y * this.y)); } // compute the distance inRange this CartPt and p double distanceTo(CartPt p){ return Math.sqrt((this.x - p.x) * (this.x - p.x) + (this.y - p.y) * (this.y - p.y)); } // create a new point that is deltaX, deltaY off-set from this point CartPt translate(int deltaX, int deltaY) { return new CartPt(this.x + deltaX, this.y + deltaY); } } |
Extend and the class hierarchy in
figures 3.1 and 3.2
to include Rectangle
s. The
extension must implement all
the abstract methods in AShape
.
Implement an extension of the class hierarchy of problem 3.5 to include a perimeter method.