1. Encapsulation
Encapsulation is the bundling of data and methods that operate on that data within a single unit (class). It restricts direct access to some of an object’s components.
Example:
csharppublic class BankAccount
{
private decimal balance;
public void Deposit(decimal amount)
{
if (amount > 0)
{
balance += amount;
}
}
public decimal GetBalance()
{
return balance;
}
}
2. Inheritance
Inheritance allows a class to inherit properties and methods from another class, promoting code reusability.
Example:
cshapublic class Account
{
public decimal Balance { get; set; }
public virtual void Deposit(decimal amount)
{
Balance += amount;
}
}
public class SavingsAccount : Account
{
public decimal InterestRate { get; set; }
public void ApplyInterest()
{
Balance += Balance * InterestRate;
}
}
3. Polymorphism
Polymorphism allows methods to do different things based on the object that it is acting upon, typically achieved through method overriding or interface implementation.
Example:
csharpublic class Account
{
public virtual void Withdraw(decimal amount)
{
// Default withdrawal implementation
}
}
public class CheckingAccount : Account
{
public override void Withdraw(decimal amount)
{
// Specific withdrawal implementation for CheckingAccount
}
}
public class SavingsAccount : Account
{
public override void Withdraw(decimal amount)
{
// Specific withdrawal implementation for SavingsAccount
}
}
4. Abstraction
Abstraction is the concept of hiding the complex implementation details and showing only the essential features of the object.
Example:
cshapublic abstract class Account
{
public abstract void Withdraw(decimal amount);
}
public class CheckingAccount : Account
{
public override void Withdraw(decimal amount)
{
// Implementation for CheckingAccount
}
}
public class SavingsAccount : Account
{
public override void Withdraw(decimal amount)
{
// Implementation for SavingsAccount
}
}
Summary
These OOP concepts in .NET help organize and structure your code effectively, making it easier to manage and extend. Understanding these principles is essential for building robust applications in the .NET framework.
No comments:
Post a Comment