Inheritance in Object-Oriented Programming
Inheritance is one of the core principles of Object-Oriented Programming (OOP). It allows a class (child class) to inherit properties and behaviors (methods) from another class (parent class). This promotes code reusability and establishes a natural relationship between objects.
Why Is Inheritance Important?
- Code Reusability: Eliminates redundant code by allowing child classes to reuse parent class logic.
- Hierarchy and Organization: Helps structure related classes efficiently.
- Extensibility: Enables adding new functionalities without modifying existing code.
How Inheritance Works
In C#, we use the :
symbol to define inheritance.
Example:
// Parent class
class BankAccount
{
protected double balance;
protected string owner;
public BankAccount(string owner, double initialBalance)
{
this.owner = owner;
balance = initialBalance > 0 ? initialBalance : 0;
}
public void Deposit(double amount)
{
if (amount > 0)
{
balance += amount;
Console.WriteLine($"{owner} deposited: {amount}");
}
}
public double GetBalance()
{
return balance;
}
}
// Child class inheriting from BankAccount
class SavingsAccount : BankAccount
{
private double interestRate;
public SavingsAccount(string owner, double initialBalance, double interestRate)
: base(owner, initialBalance)
{
this.interestRate = interestRate;
}
public void ApplyInterest()
{
balance += balance * interestRate;
Console.WriteLine($"Interest applied to {owner}'s account.");
}
}
// Using inheritance
var savings = new SavingsAccount("John Doe", 1000, 0.05);
savings.Deposit(500);
savings.ApplyInterest();
Console.WriteLine($"{savings.GetBalance()}");
Key Takeaways:
SavingsAccount
inherits from BankAccount
, reusing its methods.
SavingsAccount
extends functionality by adding an interest rate feature.
- The
base
keyword allows calling the parent class constructor.
Conclusion
Inheritance simplifies code maintenance, promotes reusability, and helps in designing flexible systems. It is a powerful feature that establishes relationships between classes and enables effective hierarchy management.
In the next articles, we will explore more Object-Oriented Programming principles such as Interfaces and Polymorphism, continuing with our structured examples.