©2008 Felleisen, Proulx, et. al.

4  Designing Methods – Part 2

Methods for Unions and Self-Referential Data

We will focus on geometric shapes - a circle, a square, and a shape that is a combination of two shapes, the top and the bottom one. Recall the data definition as given by the class diagram:

                        +-------+                            
                        | Shape |<--------------------------+
                        +-------+                           |
                        +-------+                           |
                            |                               |
                           / \                              |
                           ---                              |
                            |                               |
         ---------------------------------------            |
         |                  |                  |            |
  +--------------+   +--------------+   +--------------+    |
  | Square       |   | Circle       |   | Combo        |    |
  +--------------+   +--------------+   +--------------+    |
+-| Posn nw      | +-| Posn center  |   | Shape top    |----+
| | int size     | | | int radius   |   | Shape bottom |----+
| | IColor color | | | IColor color |   +--------------+ 
| +-------------+  | +--------------+                     
+----+ +-----------+
     | |
     v v
  +-------+
  | Posn  |
  +-------+
  | int x |
  | int y |
  +-------+

  1. Design the method totalArea that computes the total area of a shape. For the shape that consists of two components add the areas - as if you were measuring how much paint is needed to paint all the components.

    You will need to use math functions, such as square root. The following example shows how you can use the math function, and how to test doubles for equality. (You can only make sure they are different only within some given tolerance.)

    Last modified: Tuesday, January 29th, 2008 1:18:48am