Understanding Inheritance
Learn how to reuse and extend code by creating subclasses.
Learning Objectives
- Understand the Parent-Child relationship in classes
- Create a subclass that inherits from a parent class
- Override methods to change behavior
- Use the `super()` function
Reusing Code
One of the greatest strengths of OOP is Inheritance. It allows a new class to take on the attributes and methods of an existing class.
This helps avoid repeating code. For example, both a Cat and a Dog are Animals. Instead of writing “eating” logic for both, we can write it once in an Animal class.
Parent and Child Classes
- Parent Class (Base Class): The existing class you are inheriting from.
- Child Class (Derived Class): The new class that inherits from the parent.
|
|
Overriding Methods
A child class can provide its own version of a method that already exists in the parent. This is called Overriding.
|
|
Using super()
Sometimes you want to keep the parent’s logic but add something extra to it. The super() function allows you to call methods from the parent class.
|
|
Interactive Practice
Think of a Vehicle parent class. What child classes could it have? (Car, Bicycle, Plane). What methods would they share (e.g., move) and which would be unique (e.g., fly)?
Quiz
Complete this quiz with a minimum score of 80% to mark Day 17 as complete.
Discussion
Have questions or want to discuss this lesson? Join the conversation below!