Object-oriented programming (OOP) is a programming paradigm centered around "objects" that contain both data (attributes) and code (methods) to manipulate that data. It's a powerful approach for structuring software, making it more modular, reusable, and easier to maintain. Encapsulation, abstraction, inheritance, and polymorphism are the four fundamental principles that underpin OOP. Understanding these concepts is crucial for writing effective and well-designed C# code, especially when building web applications.
Encapsulation is the bundling of data (attributes) and methods that operate on that data into a single unit, or class. It also involves controlling access to the internal state of an object, preventing direct modification from outside the object. This is achieved through access modifiers like public, private, protected, and internal.
public: Members are accessible from anywhere.private: Members are only accessible from within the same class.protected: Members are accessible from within the same class and its derived classes.internal: Members are accessible from within the same assembly (project).protected internal: Members are accessible from within the same assembly and derived classes in other assemblies.public class BankAccount
{
private string accountNumber; // Private attribute
private decimal balance; // Private attribute
public BankAccount(string accountNumber, decimal initialBalance)
{
this.accountNumber = accountNumber;
this.balance = initialBalance;
}
public string GetAccountNumber() // Public method to access accountNumber
{
return accountNumber;
}
public decimal GetBalance() // Public method to access balance
{
return balance;
}
public void Deposit(decimal amount) // Public method to modify balance
{
if (amount > 0)
{
balance += amount;
}
}
public void Withdraw(decimal amount) // Public method to modify balance
{
if (amount > 0 && amount <= balance)
{
balance -= amount;
}
}
}
public class Example
{
public static void Main(string[] args)
{
BankAccount account = new BankAccount("1234567890", 1000);
Console.WriteLine("Account Number: " + account.GetAccountNumber());
Console.WriteLine("Balance: " + account.GetBalance());
account.Deposit(500);
Console.WriteLine("Balance after deposit: " + account.GetBalance());
account.Withdraw(200);
Console.WriteLine("Balance after withdrawal: " + account.GetBalance());
// account.balance = -1000; // This would cause an error because balance is private
}
}
In this example, accountNumber and balance are private attributes, meaning they can only be accessed or modified from within the BankAccount class. Public methods like GetAccountNumber, GetBalance, Deposit, and Withdraw provide controlled access to these attributes. This prevents direct manipulation of the account's state from outside the class, ensuring data integrity.