What is Inheritance in OOP with Example
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows one class to inherit properties and behaviors from another class. This concept is based on the idea of modeling real-world relationships, where a child can inherit certain characteristics from its parents. In OOP, inheritance enables code reuse, promotes modularity, and enhances the organization of code. This article will explore the concept of inheritance in OOP, with a practical example to illustrate its usage.
At its core, inheritance is a mechanism that establishes a relationship between two classes: a parent class (also known as a superclass or base class) and a child class (also known as a subclass or derived class). The child class inherits the attributes and methods of the parent class, which can be used directly or overridden to create more specialized behavior.
To demonstrate inheritance in OOP, let’s consider a simple example involving a vehicle hierarchy. We will create a parent class called “Vehicle” and two child classes, “Car” and “Bike,” which inherit from the “Vehicle” class.
“`python
class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def start(self):
print(f”{self.brand} {self.model} is starting.”)
def stop(self):
print(f”{self.brand} {self.model} is stopping.”)
class Car(Vehicle):
def __init__(self, brand, model, doors):
super().__init__(brand, model)
self.doors = doors
def drive(self):
print(f”{self.brand} {self.model} with {self.doors} doors is driving.”)
class Bike(Vehicle):
def __init__(self, brand, model, gears):
super().__init__(brand, model)
self.gears = gears
def ride(self):
print(f”{self.brand} {self.model} with {self.gears} gears is riding.”)
“`
In this example, the “Vehicle” class serves as the parent class, containing common attributes and methods such as “brand,” “model,” “start,” and “stop.” The “Car” and “Bike” classes are child classes that inherit from the “Vehicle” class. They add their specific attributes and methods, such as “doors” and “drive” for “Car,” and “gears” and “ride” for “Bike.”
By utilizing inheritance, we can create instances of “Car” and “Bike” and call their methods, which will also execute the methods from the “Vehicle” class:
“`python
car = Car(“Toyota”, “Corolla”, 4)
car.start()
car.drive()
car.stop()
bike = Bike(“Honda”, “Cruiser”, 6)
bike.start()
bike.ride()
bike.stop()
“`
This example showcases how inheritance in OOP simplifies code by promoting code reuse and providing a clear structure for organizing classes. By establishing relationships between classes, inheritance allows developers to create more maintainable and scalable codebases.