Inheritance: Hierarchical Classification and Shared DNA
The Threat of Redundancy (WET Code)
In any computational system, duplicating logic is a severe architectural failure. If you are building a 2D physics engine, you might have a Circle and a Rectangle. Both are geometric shapes, and both undergo kinematic motion.
If you write the position (), velocity (), and the integration logic (update()) inside every single shape class, you violate the DRY (Don't Repeat Yourself) principle. A change to your integration algorithm requires you to hunt down and update every shape manually.
{/* prettier-ignore */}
The Solution: The "Is-A" Relationship
Inheritance solves this by allowing you to extract the common "DNA" into a Base Class (or Superclass). We can define a KinematicBody class that handles all positional and velocity math.
Then, Circle and Rectangle can extend this base class. Because a Circle is-a KinematicBody, it automatically inherits the physics engine's core capabilities, leaving the subclass to only worry about its specific geometric traits (like calculating area).
{/* prettier-ignore */}
The super Keyword and Overriding
Sometimes, a subclass needs to modify or add to the parent's behavior. This is called Overriding. In JavaScript, the super keyword acts as a bridge to the parent class.
If we want a GravitationalBody that applies gravity before performing standard kinematic integration, we override the update() method, apply our local acceleration, and then call super.update(dt) to let the parent finish the math.
| Keyword / Concept | Architectural Purpose |
|---|---|
extends | Establishes the rigid "is-a" structural link between classes. |
super() | Initializes the inherited State. Must be called before accessing this. |
super.method() | Delegates execution back to the parent's original Behavior. |
{/* prettier-ignore */}
The Architectural Warning: Tight Coupling
While inheritance prevents code duplication, it introduces the tightest form of Coupling in software design. The child is permanently bolted to the parent.
If you design your hierarchy poorly (known as the Fragile Base Class problem), a single modification to KinematicBody could catastrophically break every geometric shape in your engine. We will address how to escape this trap in Lesson 08: Composition.
What You Have Learned
- Taxonomy mapping: Inheritance allows you to model real-world classifications (e.g., specific geometries inheriting from general physics bodies).
extendsandsuper: The syntactic mechanisms for linking subclasses to their parents and sharing constructor logic.- Method Overriding: Refining inherited behavior by intercepting a method call and injecting local logic before delegating back to the parent.
- The Coupling Trade-off: Inheritance solves redundancy but introduces rigid dependencies.
In the next lesson: Polymorphism — how to leverage this shared DNA to issue a single command that controls an array of vastly different entities.