24 Oct 2023
In object-oriented programming, inheritance allows you to create new classes (derived) based on existing ones (base). The derived class inherits properties and behaviors from the base class.
Here's how inheritance works in OOP:
-
Base Class (Superclass):
- The base class is also known as the superclass or parent class.
- It contains attributes (data members) and methods (functions) that can be used by the derived classes.
- The base class is the starting point of the inheritance hierarchy.
-
Derived Class (Subclass):
- The derived class is also known as the subclass or child class.
- It inherits the attributes and methods of the base class.
- The derived class can also add its own attributes and methods or override the methods inherited from the base class.
- It specializes or extends the functionality of the base class.
Example of inheritance:
Base Class (Superclass): Vehicle
- Properties (Attributes): color, fuelType, speed
- Methods: start(), stop(), accelerate(), brake()
Derived Class (Subclass): Car
- Inherits from: Vehicle
- Additional Properties: brand, model
- Additional Methods: honkHorn()
Derived Class (Subclass): Bicycle
- Inherits from: Vehicle
- Additional Properties: type (e.g., road bike, mountain bike)
- Additional Methods: ringBell()
In this generic example, the base class Vehicle defines common properties and methods that are shared by all vehicles, such as cars and bicycles. The derived class Car inherits from Vehicle and adds properties and methods specific to cars, like brand and model. Similarly, the Bicycle class also inherits from Vehicle but introduces properties and methods specific to bicycles.
This inheritance structure allows you to create instances of both Car and Bicycle that inherit the common attributes and methods from the Vehicle class while having their specialized features.