3.4  Example: Data definitions for a combination of shapes

A Shape is on of:

Note: For clarity, we start the names of abstract classes with the letter A.

/*
                        +-------------+                           
                        | AComboShape |<-------------------------+
                        +-------------+                          |
                        +-------------+                          |
                              / \                                |
                              ---                                |
                               |                                 |
         -----------------------------------------               |
         |                 |                     |               |
  +-------------+    +------------+    +--------------------+    |
  | Circle      |    | Rect       |    | Combo              |    |
  +-------------+    +------------+    +--------------------+    |
  | Posn center |    | Posn nw    |    | AComboShape top    |----+
  | int radius  |    | int width  |    | AComboShape bottom |----+
  +-------------+    | int height |    +--------------------+ 
                     +------------+                           
*/

// to represent a combination of shapes
abstract class AComboShape {
}

// to represent a circle on the canvas
class Circle extends AComboShape {
  Posn center;
  int radius;

  Circle(Posn center, int radius) {
    this.center = center;
    this.radius = radius; }
}

// to represent a rectangle on a canvas
class Rect extends AComboShape {
  Posn nw;
  int width;
  int height;

  Rect(Posn nw, int width, int height) {
    this.nw = nw;
    this.width = width;
    this.height = height; }
}

// to represent a combination of two shapes
class Combo extends AComboShape {
  AComboShape top;
  AComboShape bottom;

  Combo(AComboShape top, AComboShape bottom) {
    this.top = top;
    this.bottom = bottom;
  }
}

// Intreractions:
Examples of the use of the constructors for the subclasses of AComboShape

Circle c1    = new Circle(new Posn(10, 20), 15);
Circle c2    = new Circle(new Posn(40, 20), 10);
Rect r1      = new Rect(new Posn(10, 20), 20, 40);
Rect r2      = new Rect(new Posn(40, 20), 50, 10);
Combo combo1 = new Combo(c1, r1);
Combo combo2 = new Combo(r2, combo1);
Combo combo3 = new Combo(combo2, c2);

// Challenge: paint this shape
// assume the colors are c1: red, c2: blue, r1: green, r2: yellow