Inheritance

These notes do not replace the material about inheritance presented in class and the textbook. It is a supplement.

We have written a class Race which is part of a package concurrency. (This class detects data races in concurrent Java programs. However, what this class actually does is not important at all for this example.) Some of the methods of the class Race throw exceptions. To make sure that these exceptions are different from exceptions thrown by other methods (to make life of the client simpler), we create our own exception class. We extend the class Exception. The API of the extended class can be found here. No attributes are added, no methods are added, no methods are overridden. We only define constructors in the class RaceException.

We extend the class Rectangle. The class Square represents a special type of Rectangle. Its API can be found here. Note that everything you can do with a Rectangle, you can also do with a Square. The class Square is merely introduced for convenience. No attributes are added. No methods are overridden. Of course, we need to define constructors. We add the methods getSide and setSide, also just for convenience.

The class CanadianBanknote represents a Canadian banknote. The newer banknotes have a hologram. These are represented by the class CanadianBanknoteWithHologram which is a subclass of CanadianBanknote. Its API can be found here. This time we add a single attribute, hologram, that represents the hologram of the banknote. Also in this case, no methods are overridden (a 20 dollar bill with hologram and a 20 dollar bill without hologram are still considered to be the same). We add the method getHologram and constructors.

We extend the class Rectangle again. This time, we consider Rectangles that have a Color: ColouredRectangle. Its API can be found here. This time we add an attribute that represents the colour of the Rectangle. We add the methods getColour and setColour to manipulate the colour of the Rectangle. We add constructors. This time we override the methods equals and toString.

The classes Cube and RightTriangularPrism have some attributes (height) and methods (getHeight, equals, toString) in common. Some of the code in these two classes is identical (the attribute height and the method getHeight, for example). To avoid code duplication, we introduce a common superclass Prism. Since this class does not represent concrete entities, we declare it abstract. The classes Cube and RightTriangularPrism extends the class Prism.

The classes such as Rectangle and Square all have a getArea method. This commonality can be captured by the interface Shape and by specifying that all classes implement this interface.