This example shows how private fields are protected and accessed only through public methods (getters/setters):
public class BankAccount
{
// Private field: cannot be accessed directly from outside the class
private decimal balance;
// Public method to deposit money (with controlled access)
public void Deposit(decimal amount)
{
if (amount > 0)
{
balance += amount;
}
}
// Public method to withdraw money (example of validation)
public void Withdraw(decimal amount)
{
if (amount > 0 && amount <= balance)
{
balance -= amount;
}
}
// Public getter for balance (read-only access)
public decimal GetBalance()
{
return balance;
}
}
// Usage example:
var account = new BankAccount();
account.Deposit(100);
account.Withdraw(40);
Console.WriteLine(account.GetBalance()); // Output: 60
This demonstrates encapsulation because the balance field is hidden from direct access,
and all interactions with it go through controlled methods.
No comments:
Post a Comment