Inheritance Hierarchy Class Diagram
The code
classDiagram
class Shape {
+String color
+area() float
}
class Circle {
+float radius
+area() float
}
class Rectangle {
+float width
+float height
+area() float
}
class Square {
+area() float
}
Circle --|> Shape
Rectangle --|> Shape
Square --|> Rectangle
How this template works
The shape hierarchy is the classic inheritance example for a reason: it shows a base contract, specializations, and an override chain in four small classes. Shape declares color and an area() method. Circle and Rectangle extend it with their own fields. Square extends Rectangle, inheriting width and height while overriding area() to enforce the equal-sides invariant. In three relationship lines you can teach polymorphism, method overriding, and why deep hierarchies need a justification.
The syntax centers on one arrow. Circle --|> Shape is inheritance, drawn as a solid line with a hollow triangle pointing at the parent, and the child always sits on the left. Repeat the arrow once per subclass, as this file does, rather than trying to merge subclasses onto one line. Inside the blocks, +String color is a public attribute and +area() float is a public method with a return type. Notice that area() appears in every class: repeating it is how the diagram documents that each subclass provides its own implementation, and readers scan for that repetition to find the override points.
The gotcha is hierarchy depth. Three levels, as drawn here, reads fine; five levels starts hiding behavior in the middle of the chain, and the diagram cannot show you which area() actually runs for a Square without careful reading. If you find yourself adding a fourth or fifth level, consider composition instead and draw plain associations. Also keep the parent on the right side of the arrow — flipping it reverses the meaning for every reader.
To adapt the template, add a Triangle class beside Circle, add a describe() method to the base and override it everywhere, or add a Painter class associated with Shape to show composition alongside inheritance.
Related templates that extend these ideas: the strategy pattern class diagram for realization instead of inheritance, the API SDK class diagram for a practical two-level hierarchy, and the domain model class diagram for association-heavy models. The class diagram guide documents all relationship arrows.
Variations to try
- Add a Triangle class at the same level as Circle to extend the hierarchy horizontally.
- Add a describe method to the base class and override it in each subclass.
- Add a Painter class associated with Shape to show composition alongside inheritance.