Inheritance Fundamentals
You'll learn how to extend existing classes to create specialized versions that automatically reuse parent code while adding new features.
The Core Idea
Inheritance lets you define a new class based on an existing one. The new class (called a subclass or child class) automatically receives all the properties and behaviors from the original class (the superclass or parent class), and can add or modify functionality without rewriting shared code.
Think of inheritance like biological family trees: children inherit traits from parents but also develop their own unique characteristics. A "Dog" class might inherit from an "Animal" class—every dog is an animal, so it makes sense for Dog to reuse Animal's basic properties like "age" and "eat()" while adding dog-specific features like "bark()".
How It Works
When you declare a subclass, you specify which parent class to extend. The subclass:
- Inherits all accessible fields and methods from the parent
- Can add new fields and methods unique to itself
- Can override parent methods to provide specialized behavior
This creates a class hierarchy—a tree structure where general concepts sit at the top and more specific ones branch downward. An "Animal" might have subclasses "Dog" and "Cat", and "Dog" might have its own subclass "Retriever".
Why It Matters
Inheritance promotes code reuse: write shared logic once in the parent, then specialize only what differs in children. It also models real-world "is-a" relationships naturally—a retriever is a dog, which is an animal.
Key Takeaway: Inheritance creates subclass hierarchies where child classes automatically reuse parent properties and methods, enabling code reuse and natural modeling of specialized concepts.