Abstraction in Object-Oriented Programming
Abstraction is one of the key principles of Object-Oriented Programming (OOP). It is the process of hiding implementation details and exposing only the necessary functionalities. This helps in reducing complexity and improving code maintainability.
Why Use Abstraction?
- Hides Complexity: Users only interact with relevant functionalities.
- Improves Maintainability: Changes in the implementation do not affect the users of the class.
- Enhances Code Reusability: Common functionalities can be defined in base classes and shared across multiple derived classes.
How Abstraction Works
Abstraction in C# can be achieved using abstract classes and interfaces.
Example:
// Abstract class
abstract class BankAccount
{
protected double balance;
protected string owner;
public BankAccount(string owner, double initialBalance)
{
this.owner = owner;
balance = initialBalance > 0 ? initialBalance : 0;
}
public abstract void Deposit(double amount);
public abstract double GetBalance();
}
// Derived class implementing the abstract methods
class SavingsAccount : BankAccount
{
public SavingsAccount(string owner, double initialBalance) : base(owner, initialBalance) { }
public override void Deposit(double amount)
{
if (amount > 0)
{
balance += amount;
Console.WriteLine($"Deposited: {amount}");
}
}
public override double GetBalance()
{
return balance;
}
}
var account = new SavingsAccount("John Doe", 1000);
account.Deposit(500);
Console.WriteLine($"Current Balance: {account.GetBalance()}");
Key Takeaways:
- The
BankAccount
class is abstract, meaning it cannot be instantiated directly.
- It defines abstract methods (
Deposit
and GetBalance
) that must be implemented by derived classes.
SavingsAccount
provides concrete implementations for these methods, ensuring proper behavior.
Conclusion
Abstraction simplifies code by hiding unnecessary details while exposing only essential functionalities. It enhances code flexibility, readability, and maintainability.
In the next articles, we will explore other Object-Oriented Programming principles such as Inheritance and Interfaces using a consistent example structure.