From a purely technical point of view, inheritance is a mechanism for code reuse. It allows us to make a new class that automatically gets the properties and behaviors of an existing class without us having to write them in the new class. For example, we can define a class Dog and say it should have all the member variables and methods of the class Animal.
It also allows for writing code that works on any object of related classes. If both Dogs and Cats inherit from Animal, we can write one function that works with any type of Animal and it will work with both Dogs and Cats.
Conceptually, inheritance represents an "is-a" relationship between a more general class (the superclass or parent class) and a more specific class (the subclass or child class). A Dog is-an Animal and so is Cat, so we could describe both of them as subclasses of Animal. The fact that Dog is-an Animal explains why Dog
classDiagram
class Animal {
...details omitted...
}
class Dog {
...details omitted...
}
class Cat {
...details omitted...
}
Animal <|-- Dog
Animal <|-- Cat
Inheritance can extend to multiple levels and create complex hierarchies of relationships. For example, we might categorize different kinds of Shapes using this set of inheritance relationships:
Circle, Quadrilateral, and Triangle are subclasses of Shape. Rectangle and Trapezoid are subclasses of Quadrilateral. Square is a subclass of Rectangle. EquilateralTriangle is a subclass of Triangle.
classDiagram
class Shape {
...details omitted...
}
class Circle {
...details omitted...
}
class Quadrilateral {
...details omitted...
}
class Trapezoid {
...details omitted...
}
class Rectangle {
...details omitted...
}
class Square {
...details omitted...
}
class Triangle {
...details omitted...
}
class EquilateralTriangle {
...details omitted...
}
Shape <|-- Circle
Shape <|-- Quadrilateral
Shape <|-- Triangle
Triangle <|-- EquilateralTriangle
Quadrilateral <|-- Rectangle
Quadrilateral <|-- Trapezoid
Rectangle <|-- Square
The is-a relationship extends to the subclasses of a subclass. So, in the diagram above, we would say that Square is-a Shape. Even though there is no direct line from square to shape, Square is a Rectangle, Rectangle is a Quadrilateral, and Quadrilateral is a Shape, so therefore Square is-a Shape.
F is a subclass of B. F and D are subclasses of A. A and C are subclasses of E. G is a subclass of C.
classDiagram
class A {
...details omitted...
}
class B {
...details omitted...
}
class C {
...details omitted...
}
class D {
...details omitted...
}
class E {
...details omitted...
}
class F {
...details omitted...
}
class G {
...details omitted...
}
B <|-- F
A <|-- B
A <|-- D
E <|-- A
E <|-- C
C <|-- G