What is inheritance example? Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class to inherit properties and methods from another class. This concept is essential for creating reusable and modular code. By understanding inheritance, developers can build more efficient and scalable applications. In this article, we will explore what inheritance is and provide a practical example to illustrate its usage.
Inheritance is based on the idea of “is-a” relationship between classes. For instance, consider a simple hierarchy of classes related to vehicles. We can have a base class called “Vehicle,” which contains common properties and methods shared by all types of vehicles. Then, we can create derived classes, such as “Car,” “Truck,” and “Bike,” which inherit from the “Vehicle” class. This way, each derived class can have its unique properties and methods while still retaining the common characteristics of a vehicle.
Let’s take a closer look at an example in Python, a popular programming language that supports OOP:
“`python
class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def start_engine(self):
print(f”The {self.brand} {self.model}’s engine is starting.”)
class Car(Vehicle):
def __init__(self, brand, model, doors):
super().__init__(brand, model)
self.doors = doors
def drive(self):
print(f”The {self.brand} {self.model} with {self.doors} doors is driving.”)
class Truck(Vehicle):
def __init__(self, brand, model, cargo_capacity):
super().__init__(brand, model)
self.cargo_capacity = cargo_capacity
def load_cargo(self):
print(f”The {self.brand} {self.model} is loading cargo with a capacity of {self.cargo_capacity} tons.”)
Creating instances of derived classes
my_car = Car(“Toyota”, “Corolla”, 4)
my_truck = Truck(“Ford”, “F-150”, 1000)
Using inherited methods
my_car.start_engine()
my_car.drive()
my_truck.start_engine()
my_truck.load_cargo()
“`
In this example, we have a base class “Vehicle” with an `__init__` method that initializes the brand and model properties. The `start_engine` method is also defined in the base class. The derived classes “Car” and “Truck” inherit from the “Vehicle” class and add their specific properties and methods.
By using inheritance, we can create instances of “Car” and “Truck” and call methods like `start_engine`, `drive`, and `load_cargo` without having to redefine them in each derived class. This makes our code more modular and easier to maintain.
In conclusion, inheritance is a powerful concept in OOP that allows for code reuse and modularity. By understanding what inheritance is and how to use it effectively, developers can create more robust and scalable applications.