link: OOP
Inheritance
Overview
Inheretence is a fundamental concept in object-oriented programming that allows new classes to be created based on existing classes, enhancing code reusability and efficiency. By deriving a class from an existing one, new functionalities can be added or existing ones modified without the need to rewrite code.
Abstract
Inheritance ensures that subclasses inherit the public and protected members of their parent class. However, it also mandates that subclasses cannot hide these inherited methods, nor can they avoid implementing the abstract methods defined in the superclass unless they themselves are declared abstract.
While most object-oriented languages restrict a class to inherit from only one superclass, they allow implementing multiple interfaces. This provides flexibility in adopting multiple behaviors or contracts, even though all subclasses of a class implementing an interface must also conform to that interface.
Content
Why Use Inheritance?
- Code Reusability: Inheritance promotes the reuse of existing code. You can create a new class from an existing class, modifying or extending it as needed.
- Simplicity: By using inherited properties and methods, new classes can be written with less code and complexity.
- Enhances the Polymorphic Behavior of the application .
Implementation Overview
In C#, inheritance is implemented using the :
symbol where the class on the right is the base class, and the class on the left is the derived class.
Base and Derived Classes
Consider the
Vehicle
class as a base class andCar
as a derived class which extendsVehicle
:
Restricting Inheritance
To prevent a class from being inherited, C# uses the Sealed Keyword. Attempting to derive from a sealed class will result in a compilation error:
Error
This use of sealed
ensures that the class cannot be extended, maintaining control over the inheritance chain and behavior customization.