Scaling shapes

exercise No. 156

Q:

We want shapes to be scalable:

In the above example the rectangle is being inflated whereas the circle is being shrunk to half its original size. Add a corresponding scale(...) method to the Shape inheritance hierarchy which allows for operation chaining as well.

Provide appropriate unit tests.

A:

This task is pretty much straightforward. Since scaling requires specific details (like radius or width and height) a scale() method cannot be implemented on top level of our inheritance hierarchy. We thus start by defining an abstract method in our class Shape:

/**
  *
  * @param factor Scale the current shape by this value.
  * @return The current object.
  */
public abstract Shape scale(double factor);

This method has to be implemented in our two concrete classes Circle and Rectangle.

Sensible unit tests may be based on the observation that:

  • A shape's perimeter grows linear with the scaling factor.

  • A shape's area grows linear with the scaling factor's square.