Inheritance
C# Inheritance
Inheritance in C# allows one class to acquire the properties, methods, and behaviors of another class. This promotes code reusability, extensibility, and better organization of code.
Key Features of Inheritance
Base Class (Parent)
The class being inherited from.
Defines shared properties and methods.
Derived Class (Child)
The class inheriting from the base class.
Can add or override functionality.
Access Modifiers
public: Accessible to derived classes and outside the class.protected: Accessible only within the class and derived classes.private: Not accessible in derived classes.
Syntax
Use the colon (
:) to define inheritance.
Types of Inheritance
1. Single Inheritance
A single derived class inherits from one base class.
Example:
2. Hierarchical Inheritance
Multiple derived classes inherit from a single base class.
Example:
3. Multilevel Inheritance
A derived class inherits from another derived class.
Example:
4. Multiple Inheritance
Not supported directly in C# to avoid ambiguity.
Achieved using interfaces.
Example (using interfaces):
Inheritance with Access Modifiers
Modifier
Base Class Accessibility
Derived Class Accessibility
public
Accessible everywhere.
Accessible everywhere.
protected
Not accessible outside.
Accessible in derived classes.
private
Only accessible within class.
Not accessible in derived class.
Overriding and Virtual Methods
1. Virtual and Override Methods
Virtual methods in the base class can be overridden in the derived class.
Example:
2. Sealed Methods
Prevent further overriding in derived classes.
Example:
Abstraction
Abstraction in C# allows you to hide the implementation details and show only the essential features of an object. It helps in reducing complexity and allows you to focus on what an object does instead of how it does it.
Abstract Classes
Abstract Class: Cannot be instantiated and may contain abstract methods that must be implemented by derived classes.
Abstract Method: A method without a body that must be overridden in derived classes.
Example:
Interfaces
Interface: Defines a contract that implementing classes must fulfill. Interfaces can contain methods, properties, events, and indexers but no implementation.
Example:
Summary
Abstraction: Hides complex implementation details and shows only the necessary features.
Abstract Classes: Define methods to be implemented by derived classes.
Interfaces: Define a contract for classes to implement.
Abstraction helps in managing complexity and focusing on the relevant aspects of an object, making your code more modular and easier to maintain. Combining inheritance and abstraction can lead to highly reusable and flexible code structures.