4.1 What is Inheritance?
Inheritance is a core mechanism of OOP where a newly derived class (subclass / child class) automatically inherits all non-private fields and methods from an existing class (superclass / parent class).
Inheritance represents an "IS-A" relationship. For example, a Dog IS-A Animal, and a Manager IS-A Employee. It forms a clean taxonomic hierarchy, dramatically eliminates boilerplate code duplication, and enables subtype polymorphism.
4.2 Types of Inheritance
OOP taxonomies are structured using five distinct inheritance models:
- Single Inheritance: A child class inherits directly from exactly one parent class (e.g.,
class B extends A). Supported across all OOP languages. - Multilevel Inheritance: A class inherits from a parent that itself is a subclass, forming an inheritance chain (e.g.,
A → B → C). - Hierarchical Inheritance: Multiple distinct subclasses inherit from a single common parent class (e.g., both
CatandDoginherit fromAnimal). - Multiple Inheritance: A single class inherits from two or more distinct parent classes simultaneously (e.g.,
class C extends A, B). Supported in C++ and Python; Java disallows multiple class inheritance to avoid the Diamond Problem, supporting it via multiple interfaces instead. - Hybrid Inheritance: A composition combining two or more of the above models into a single architecture.
Figure 4.1: The five structural models of object-oriented class inheritance.
4.3 The 'super' Keyword & Method Overriding Basics
When a child class redefines a method that already exists in its parent class with the exact same name, return type, and parameter list, it performs Method Overriding.
The super Keyword
Subclasses frequently need to augment rather than completely erase parent behavior. The super keyword provides an explicit reference to the immediate superclass:
- Invoking Parent Constructors:
super(name, age);must be the first statement inside a child constructor. - Accessing Shadowed Fields & Methods: If a subclass overrides
printDetails(), callingsuper.printDetails()executes the parent's base logic before executing child customizations.