107. The Shapes demo - Inheritance
The class hierachy for the Shapes demo is provided below:
Inheritance is used in a number of places:
- The
Squareclass is a subclass ofRectangleas squares are a special type of rectangle in which all four sides have the same length.-
Squaredoesn’t need to do much over the already providedRectangleclass
-
- The
Triangleclass is extended by two subtypes:TriangleRightAngledandTriangleIsosceles-
TriangleEquilateralis a subclass ofTriangleIsosceles
-
The three Triangle subtypes encapsulate specific refinements such as the definition of the sides and refinement of the calculateArea calculation. By making calculateArea a static method, each subtype makes the calculation easily available to other code as well as tying the calculateArea instance method to the static method.
The Square, TriangleRightAngled and TriangleEquilateral classes are both declared as final because I decided they couldn’t be refined any further. This is an important aspect to designing/developing classes: only allow for inheritance if you will support it. By marking these classes as final I’ve indicated that the implementations can’t/shouldn’t be further enhanced. Naturally, another developer could extend Triangle with their own implementation as it isn’t marked as final because I believe Triangle to be a sound generic basis for describing triangles.