Advanced Topic 42 of 54 Programming Fundamentals
Inheritance
Deriving a new type that reuses and extends an existing one.
How it works
A subclass inherits the fields and methods of a base class and can add new ones or override existing ones. It models an is-a relationship and enables code reuse, with method lookup walking up the class chain at runtime. Languages differ on whether a class may have multiple parents, using interfaces or mixins to compensate.
Step-by-step walkthrough
- Animal defines shared behavior such as eat().
- Dog extends Animal and reuses eat().
- Dog adds its own bark().
- Puppy extends Dog and gets everything above it.
- Deep chains become hard to change, so keep hierarchies shallow.
Where it is used
Shape with Circle and Rectangle subclasses, exception hierarchies, UI widget toolkits and framework base classes use inheritance. It works best for stable, genuine is-a relationships.
Common pitfall
Deep hierarchies are brittle, and the fragile base class problem means base changes can break children unpredictably. Inheriting just for code reuse creates awkward couplings. Subclasses must honor the base contract. Prefer composition, keep hierarchies shallow and mark classes final when they are not designed for extension.
Where it fits in the course
Inheritance is topic 42 of 54 in Programming Fundamentals, rated Advanced. It follows Encapsulation. The next topic is Polymorphism.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Programming Fundamentals quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Programming Fundamentals quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Inheritance?
Where do people use Inheritance?
What is the most common mistake with Inheritance?
What should I learn before this topic?
How can I practice it?
Is Inheritance hard to learn?
How long does it take to learn Inheritance?
Which topics are related to Inheritance?
What should I study after Inheritance?
Related topics
- Encapsulation (Programming Fundamentals)
- Polymorphism (Programming Fundamentals)
- Classes and Objects (Programming Fundamentals)
- Abstraction (Programming Fundamentals)