Inheritance in Object- OrientedProgramming (OOP) Inheritance in Object-Oriented Programming (OOP) is a mechanism that enables one class to inherit the attributes and behaviors (fields and methods) of another class. This facilitates code reuse, allowing a new class to be derived from an existing class and either extend or alter its behavior. Here’s how it works:
2.
Key Concepts Parent (Base)Class The class from which properties and methods are inherited by another class. It is also referred to as the superclass. Child (Derived) Class The class that derives properties and methods from the parent class. It is also known as the subclass.
3.
Types of Inheritance 1 SingleInheritance A class inherits from a single parent class. 2 Multiple Inheritance A class inherits from more than one parent class. (Note: Not all programming languages support this directly; for instance, Java does not allow multiple inheritance of classes, while Python does.) 3 Multilevel Inheritance A class inherits from a child class, forming a chain of inheritance. 4 Hierarchical Inheritance Several classes inherit from one parent class. 5 Hybrid Inheritance A combination of two or more types of inheritance.
4.
Important Features ofInheritance Code Reusability The child class inherits methods and properties from the parent class, eliminating the need to duplicate existing code. Overriding A subclass can implement its own version of methods defined in the parent class. This process is known as method overriding. Accessing Parent Methods/Properties By using super(), a subclass can invoke methods or access properties from the parent class. Extending Functionality A child class can enhance or extend the functionality of the parent class without modifying the parent class itself.
5.
Example of MethodOverriding In the example above, both Dog and Cat override the speak() method. If we had not overridden the method, both would invoke the speak() method from the Animal class, which outputs "makes a sound."