Object Oriented Programming Concepts
Object Oriented Programming Concepts
Inheritance
Inheritance allows a new class to inherit properties and methods from an existing class. It enables new classes, known as derived classes or subclasses, to take on the properties and methods of existing classes, which are called base classes or superclasses.
Inheritance promotes code reusability and establishes a hierarchy between classes. It's about extending existing classes to create new ones, building upon previous work without reinventing the wheel.
Inheritance in OOP allows for structuring and organizing code more logically, making it easier to maintain and extend. It encourages the reuse of established mechanisms and builds hierarchies, making complex code more manageable.
Some benefits of inheritance include:
- Code Reusability: Avoids repetition by inheriting features from existing classes.
- Extensibility: Easier to extend the functionality of existing classes.
- Hierarchy: Establishes a natural hierarchy between classes.
Types of Inheritance
- Single Inheritance: A subclass inherits from one superclass.
- Multiple Inheritance: A subclass inherits from more than one superclass.
- Multilevel Inheritance: Involves multiple levels of inheritance, e.g. a subclass inherits from a class that is a subclass of another class.
Example: A Vehicle System
Imagine a system that models different types of vehicles.
class Vehicle:
def general_usage(self):
return "Transportation"
class Car(Vehicle):
def specific_usage(self):
return "Commute to work, vacation with family"
class Truck(Vehicle):
def specific_usage(self):
return "Transport goods"
- Here,
Car
andTruck
are subclasses ofVehicle
. Vehicle
is the Base/Superclass.- Subclasses inherit some properties/methods from
Vehicle
and also have their own specific properties/methods. - This parent/child structure (Inheritance) promotes the reuse of existing code. Car and Truck objects can reuse the code defined in Vehicle class.