B3.2.1 · OOP for multiple classes
Inheritance & hierarchies
By the end you can
Construct and trace inheritance hierarchies modeling is-a relationships with extends, super, and protected members.
In large software systems, writing duplicate attributes and methods across dozens of similar classes is inefficient and error-prone. allows a new class (the subclass or child class) to automatically absorb all non-private attributes and methods from an existing class (the superclass or parent class).
The “is-a” relationship#
Inheritance should only be used when a genuine “is-a” relationship exists in the real-world domain:
- A
Caris-aVehicle. - A
Manageris-anEmployee. - A
Circleis-aShape.
If you cannot say “Subclass is-a Superclass” naturally, inheritance is the wrong tool (you probably want composition or aggregation instead).
The super keyword#
The keyword provides a direct reference to the immediate parent class:
- Calling parent constructors: The subclass constructor must initialize the parent’s fields first using
super(args...). This call must strictly be the very first statement inside the subclass constructor body. - Calling parent methods: If a subclass overrides a parent method, calling
super.render()allows the subclass to execute the parent logic before adding its own enhancements.
+ start(): void
+ describe(): String
+ describe(): String (@Override)
+ honkHorn(): void
+ recharge(): void
Check yourself
Inheritance and super
Quick questions, made fresh every time and marked here. Do a few until they feel easy.
Exam practice
Paper 1-style questions
3 questions · 8 marks
Write your answer as you would in the exam, then show the mark points and tick each one your answer made. These are our own questions in the style of the exam, not past-paper questions.
1.Explain the concept of inheritance and describe the 'is-a' relationship using a concrete software example.
[4]Explain: Give reasons: say what happens AND why, or how one thing causes another.
2.Describe two distinct uses of the 'super' keyword in a Java subclass.
[2]Describe: A detailed account: say what happens, step by step if it is a process.
3.State two benefits of using inheritance in an object-oriented software project.
[2]State: Give a short answer, no explanation needed.
In a nutshell
- Inheritance allows a subclass to inherit attributes and methods from a parent superclass using the extends keyword.
- It models an “is-a” relationship (e.g. Dog is-a Mammal; Mammal is-a Animal).
- The super keyword invokes superclass constructors and parent methods.
- Protected access (#) allows subclasses to access fields directly while keeping them private from the outside world.
