Scaling shapes

exercise No. 171


We want shapes to become scalable:

In the above example the rectangle is being shrunk to 50% of its original size whereas the circle's radius is being doubled. Add a corresponding scale(...) method to the inheritance hierarchy which allows for operation chaining as well.

Provide appropriate unit tests.


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.