©2005 Felleisen, Proulx, et. al.

Methods and Unions of Classes

3.3  Problem (12.1.1)

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.

3.4  Problem (12.1.2)

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;
 }
}

Figure 3.1: Classes for geometric shapes with methods (part 1)


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);
 }
}

Figure 3.2: Classes for geometric shapes with methods (part 2)

3.5  Problem (12.1.3)

Extend and the class hierarchy in figures 3.1 and 3.2 to include Rectangles. The extension must implement all the abstract methods in AShape.

3.6  Problem (12.1.4)

Implement an extension of the class hierarchy of problem 3.5 to include a perimeter method.