Generalisation and inheritance
Generalisation and inheritance explain how classes relate by 'is-a' hierarchies to enable code reuse and polymorphism in object‑oriented design.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Software engineers use generalisation and inheritance when they design class hierarchies so that common behaviour and data live in one place (the parent) and specialised behaviour lives in children. This reduces duplication, enables polymorphism (one interface, many implementations) and helps structure systems for maintenance and testing.
Key ideas
Start from first principles and definitions.
Class: a blueprint that defines a set of attributes (data) and operations (methods). I define it here as a type that describes the structure and behaviour of objects.
Object: an instance of a class with concrete values for attributes.
Generalisation: the modelling relationship that identifies a common abstraction from two or more classes. Generalisation is the process of finding shared properties and putting them into a higher-level class. In UML, generalisation is shown as a solid line with a hollow triangle pointing to the general (parent) class.
Specialisation: the opposite of generalisation; deriving a more specific class from a general one by adding or refining properties.
Superclass (base class, parent): the class that provides the general behaviour and attributes.
Subclass (derived class, child): the class that inherits behaviour and may add or override it.
Inheritance: the language mechanism by which a subclass acquires the attributes and operations of its superclass. It implements the conceptual generalisation/specialisation relation in code.
Polymorphism: ability to use a superclass reference to refer to subclass objects and invoke overridden methods; behaviour depends on the actual object type at runtime (dynamic dispatch).
Method overriding: defining in a subclass a method with the same signature as one in the superclass, replacing or extending its behaviour.
Method overloading: defining multiple methods in the same class with the same name but different parameter lists (compile-time polymorphism). Not inheritance-specific but commonly confused with overriding.
Abstract class: a class that cannot be instantiated and may contain abstract methods (declared but not implemented). It is used to define an interface and partial implementation.
Interface (in the language sense): a type that declares method signatures without (necessarily) providing implementations (language-specific details differ by language version).
Multiple inheritance: a class inherits from more than one direct parent. It raises issues such as the diamond problem.
Liskov Substitution Principle (LSP): a formal correctness condition for behavioural inheritance. Exact university-style statement: "If S is a subtype of T, then objects of type T may be replaced by objects of type S without altering any of the desirable properties of the program (correctness, task performed, etc.)." More formally in terms of preconditions and postconditions: for every method m defined for T, the corresponding method in S must not strengthen the precondition and must not weaken the postcondition; invariants of T must hold for S.
Derivation (step-by-step typical exam reasoning):
- Let client code C expect to call method m on objects typed as T and assume m's precondition P_T and postcondition Q_T.
- If S strengthens the precondition (requires P_S with (P_S => P_T) true but (P_T => P_S) false), then C may not prepare the stronger requirements; substitution fails at call time.
- If S weakens the postcondition (provides Q_S with (Q_T => Q_S) true but (Q_S => Q_T) false), then C's expectations about results are violated because Q_S does not imply Q_T.
- Therefore, S must require no more (preconditions preserved or weakened) and must guarantee at least what T guarantees (postconditions preserved or strengthened).
Design consequences:
- Use inheritance when there is a true "is-a" relationship and when you need subtype polymorphism or to share implementation.
- Prefer composition (has-a) when behaviour varies independently or when you want to avoid tight coupling.
UML drawing instructions (exactly what to draw and label):
- To show a generalisation: draw two class boxes (rectangle with three compartments: name, attributes, operations). Draw a straight line from the subclass box to the superclass box. At the superclass end, draw a hollow triangle arrowhead pointing at the superclass. Label classes with their names; if abstract, italicise the name (or write {abstract}). If you need to show an overridden operation, list the operation in both boxes and optionally annotate the subclass operation with {redefines opName} or explain overriding in a note (UML uses 'redefines'; there is no standard «override» stereotype).
Common language mechanisms (conceptual): virtual methods, abstract methods, interface methods, method dispatch table (vtable) implementing dynamic dispatch, access control (public, protected, private), and final/sealed methods preventing override.
Formulas
For a programming topic we list the syntax to remember (each line is a separate syntax example). After the code line, I explain the symbols and when it applies.
class Sub extends Super { ... } — Java single inheritance syntax: Sub is the subclass, Super is the superclass. Use in Java to inherit implementation from a single superclass.
class Sub : Super { ... } — C# single inheritance syntax for classes. Use ':' to specify the base class; list interfaces after the base class separated by commas.
class Sub : public Super { ... } — C++ single inheritance syntax. public determines accessibility of inherited members to outside code and controls subtype conversion. Use when inheriting in C++.
class Sub(Super): — Python 3 class declaration for single inheritance. Use in Python; note method resolution order (MRO) matters with multiple inheritance.
virtual void f() = 0; — C++ pure virtual method declaration inside a class (makes the class abstract). virtual indicates runtime polymorphism; = 0 marks it abstract.
interface I { void f(); } — Java/C#-style interface. Declares contract with no (or limited default) implementation. Use when you only need a contract, not implementation sharing.
Java: class C implements I { ... } — a class implements an interface with 'implements'.
C#: class C : I { ... } — a class implements an interface using ':' (placed after any base class).
class Sub : public A, public B { ... } — C++ multiple inheritance syntax. Be cautious of name conflicts and diamond inheritance.
override (keyword, language-specific) — indicates an overriding method in the subclass (supported in C#, Java @Override annotation, C++11 override specifier). Use to get compiler checks that you are actually overriding.
Worked examples
Example 1 — UML and LSP model answer (exam long question) Question: Draw a UML generalisation hierarchy for Vehicle -> Car and Truck; list where LSP could be violated and how to fix. Answer (model):
- Draw three boxes labelled Vehicle, Car, Truck. Vehicle at top; draw hollow-triangle arrows from Car to Vehicle and Truck to Vehicle.
- In Vehicle, list attributes: speed, weight; operations: start(), stop(), load(cargoWeight).
- Suppose Vehicle::load(cargoWeight) assumes cargoWeight <= 1000 (precondition). If Car overrides load to require cargoWeight <= 200 (strengthened precondition), LSP is violated because code that expects to load 500 into a Vehicle would break when given a Car.
- Fixes: a) Move load to a separate interface or subclass (Loadable) implemented only by load-capable types (e.g., Truck implements Loadable). b) Make Car::load accept the same precondition (do not strengthen). c) Use composition — Car has a CargoHolder with capacity 200. This answer gets full marks by showing the diagram, stating pre/postcondition details, and listing concrete fixes.
Example 2 — Code trace illustrating dynamic dispatch (Java-like) Code (short):
class Animal { void speak() { print("...") } }class Dog extends Animal { void speak() { print("Woof") } }Animal a = new Dog(); a.speak();Trace:
- Create new Dog() → object allocated with Dog type but reference typed Animal.
- Call a.speak() → dynamic dispatch resolves to Dog.speak at runtime because speak is virtual by default in Java.
- Output: Woof. Step-by-step explains binding: compile-time checks that Animal has speak(); runtime selects Dog implementation.
Example 3 — C++ object slicing (short trace) Code:
struct B { int x; virtual void f(); };struct D : B { int y; void f() override; };D d; B b = d; // slicingWhat happens:
B b = d;constructs a new B object by copying the B subobject of d, dropping D-specific members (y) and dynamic type of b is B.- Calling
b.f();uses B::f (or if f is virtual and object is B, dispatch to B). The D parts are sliced off. This demonstrates why passing by value can break polymorphism; use pointers or references instead. Output: the D-specific behaviour is lost.
Common mistakes
- Confusing method overloading (same name, different signature) with overriding (same signature, runtime dispatch).
- Forgetting access control: inheriting private members does not make them directly accessible in subclass.
- In C++: forgetting virtual on base methods (no dynamic dispatch), and object slicing when passing by value.
- In multiple inheritance: not handling the diamond problem (duplicate base subobjects) and not using virtual base classes when needed.
- Assuming interfaces/abstract classes are identical in every language (Java, C++, Python differ in details).
For your exam
Types of questions you will face:
- Definitions and short notes (define inheritance, generalisation, LSP, abstract class).
- Draw a UML class hierarchy (diagram basics required above).
- Explain LSP with a small example and how to fix violations.
- Small code snippets: predict output and explain why (dynamic dispatch, slicing, overriding rules).
- Design question: decide between inheritance and composition and justify.
What a full-marks answer includes:
- Precise definitions of terms with bolded names (is-a relation, UML arrow description).
- Correct UML drawing instructions or a correctly drawn diagram (triangle arrow to parent; class compartments).
- Clear LSP statement with pre/postcondition reasoning and a concrete example showing violation and fix.
- For code questions: line-by-line trace, state object types, binding times (compile vs runtime), and final output.
Quick check
- What does the hollow triangle arrow in UML pointing to a class mean?
- State briefly the Liskov Substitution Principle in one sentence.
- In C++, what happens if a base class method is not declared virtual and you call it through a base pointer to a derived object?
Answers: 1) Generalisation (subclass → superclass). 2) Subtypes must be usable wherever supertypes are expected without breaking correctness (preconditions not strengthened and postconditions not weakened). 3) The base class method is called (no dynamic dispatch) — derived override is not invoked.
Note on accuracy and where I am unsure: I have tried to be precise about language syntax and LSP formulation. Please verify the exact wording for interface default methods (Java 8+) and the best phrasing of LSP in your course material; also confirm subtle C++ rules about virtual inheritance and object slicing across different compilers and standard versions.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?