CodingNic

Object-Oriented Programming

Inheritance

Object-Oriented Programming 32 min read

Inheritance

Inheritance

Sometimes classes are similar.

Instead of repeating the same code, one class can inherit from another class.

This is called inheritance.

What Is Inheritance?

Inheritance means a new class can use code from an existing class.

The existing class is called:

  • parent class
  • base class

The new class is called:

  • child class
  • derived class

Why Inheritance Matters

It helps you:

  • reuse code
  • reduce repetition
  • organize related classes
  • build larger programs

Real Example

A dog and cat are both animals.

Both may have:

  • name
  • eat()

But each can also have unique actions.

Parent Class

python
class Animal:
    def eat(self):
        print("Eating")

Child Class

python
class Dog(Animal):
    pass

pet = Dog()
pet.eat()

Output

text
Eating

Dog inherited eat() from Animal.

Add New Child Method

python
class Animal:
    def eat(self):
        print("Eating")

class Dog(Animal):
    def bark(self):
        print("Woof")

pet = Dog()
pet.eat()
pet.bark()

Output

text
Eating
Woof

Another Example

python
class Vehicle:
    def start(self):
        print("Started")

class Car(Vehicle):
    def drive(self):
        print("Driving")

car = Car()
car.start()
car.drive()

Output

text
Started
Driving

Inheriting init()

python
class Person:
    def __init__(self, name):
        self.name = name

class Student(Person):
    pass

tom = Student("Tom")
print(tom.name)

Output

text
Tom

Why This Is Powerful

You write common code once in the parent class.

Children reuse it.

Code Along

Create a class Device with method power_on().

Create child class Phone.

Run the inherited method.

Mini Challenge

Create:

  • Parent class Employee

    • method work()
  • Child class Manager

    • method lead()

Create one manager object and run both methods.

Expected output:

text
Working
Leading

Real World Use Case

Apps use inheritance for users/admins, vehicles/cars, employees/managers, enemies/bosses, and UI components.

Quiz

  1. What is inheritance?
  2. What is a parent class?
  3. What is a child class?
  4. Why is inheritance useful?

Assignment

Create a parent class Animal with method sleep(). Create child class Cat.

Summary

You learned how child classes inherit code from parent classes to reduce repetition and organize programs.