What is Encapsulation With Example Code

Encapsulation in programming, particularly in object oriented programming OOP,
refers to the bundling of data attributes or properties and
methods behaviors that operate on that data into a single unit, called a class.
This unit acts as a protective wrapper that encapsulates the internal state of an object
and hides its implementation details from the outside world.
Encapsulation allows for controlled access to the object's internal state,
providing a clear interface for interacting with the object while preventing direct manipulation of its internal data.





using System;
 
namespace ConsoleApp1
 
{
    public class BankAccount
 
    {
 
        // Private fields to encapsulate the account balance and account holder's name
 
        private decimal balance;
 
        private string accountHolderName;
 
        // Public property to access the balance (read-only)
 
        public decimal Balance
 
        {
 
            get { return balance; }
 
        }
 
        // Constructor to initialize the balance and account holder's name
 
        public BankAccount(string holderName, decimal initialBalance)
 
        {
 
            // Ensure initial balance is not negative
 
            if (initialBalance < 0)
 
            {
 
                throw new ArgumentException("Initial balance cannot be negative.");
 
            }
 
            accountHolderName = holderName;
 
            balance = initialBalance;
 
        }
 
 
 
        // Public method to deposit money into the account
 
        public void Deposit(decimal amount)
 
        {
 
            // Ensure the deposited amount is positive
 
            if (amount <= 0)
 
            {
 
                throw new ArgumentException("Deposit amount must be positive.");
 
            }
 
            balance += amount;
 
        }
 
 
 
        // Public method to withdraw money from the account
 
        public void Withdraw(decimal amount)
 
        {
 
            // Ensure sufficient balance for withdrawal
 
            if (amount <= 0 || amount > balance)
 
            {
 
                throw new ArgumentException("Invalid withdrawal amount or insufficient balance.");
 
            }
 
 
 
            balance -= amount;
 
        }
 
    }
 
 
 
    public class Program
 
    {
 
        static void Main(string[] args)
 
        {
 
            // Create a bank account object with changed parameters
 
            BankAccount account = new BankAccount("A", 100);
 
            // Accessing the balance using the property (encapsulation)
 
            Console.WriteLine("Initial Balance: $" + account.Balance);
 
            // Deposit money
 
            account.Deposit(50);
 
            Console.WriteLine("Balance after deposit: $" + account.Balance);
 
            // Withdraw money
 
            account.Withdraw(25);
 
            Console.WriteLine("Balance after withdrawal: $" + account.Balance);
 
        }
 
    } 
}