Mid
From PDF
OOP
C# OOP
Give an example of encapsulation in C#.?
Short answer: Real-World Example: Bank Account Management public class BankAccount
Example code
{
private string accountNumber; // private field
private decimal balance; // private field
public string AccountNumber { get { return accountNumber; } } // read-only public decimal Balance { get { return balance; } } // read-only public BankAccount(string accNum, decimal initialBalance)
{
accountNumber = accNum; balance = initialBalance >= 0 ? initialBalance : throw new ArgumentException("Invalid balance"); }
public void Deposit(decimal amount)
{
if(amount > 0) balance += amount; else throw new ArgumentException("Deposit must be positive"); }
public void Withdraw(decimal amount)
{
if(amount > 0 && amount <= balance) balance -= amount; else throw new InvalidOperationException("Insufficient balance"); }
} // Usage BankAccount myAccount = new BankAccount("ACC123", 1000); myAccount.Deposit(500); // Balance becomes 1500 myAccount.Withdraw(200); // Balance becomes 1300 Console.WriteLine($"Account: {myAccount.AccountNumber}, Balance: {myAccount.Balance}"); Explanation: accountNumber and balance are private, protecting sensitive data. Controlled access via methods ensures data integrity. Demonstrates real-world encapsulation in action.
Say this in the interview
- Define — one clear sentence (the short answer above).
- Example — relate it to a project like ShopNest or your real work.
- Trade-off — when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png