Encapsulation

noun

say it: “en-KAP-suh-LAY-shun” /ɛnˌkæpsəˈleɪʃən/

Keeping an object's data and the details of how it works behind its own methods, so other code can't depend on them.

What is Encapsulation?

Encapsulation means keeping an object's data private and only letting outside code change it through the object's own methods. A bank account doesn't let you set the balance directly; you must call Deposit or Withdraw, which can check the rules.

public class BankAccount
{
    private decimal balance;          // hidden

    public void Deposit(decimal amount)
    {
        if (amount <= 0) throw new ArgumentException("Deposit must be positive");
        balance += amount;
    }
}

In a sentence

  • “Thanks to encapsulation, the price could change inside the class without touching the code that used it.”

Level: Apprentice · More OOP terms at this level

Updated

In other subjects