Encapsulation is a fundamental concept in object-oriented programming that restricts direct access to an object's internal state and behavior. Instead, it provides controlled access through public methods, ensuring that the object's data remains safe and consistent.
Consider a class BankAccount
:
class BankAccount { private double balance; public BankAccount(double initialBalance) { this.balance = initialBalance; } public double getBalance() { return balance; } public void deposit(double amount) { if (amount > 0) { balance += amount; } } public void withdraw(double amount) { if (amount > 0 && amount <= balance) { balance -= amount; } } }
In this example, the balance
field is private, and its access is controlled through the getBalance
, deposit
, and withdraw
methods. This ensures that the balance cannot be modified arbitrarily.
private
and protected
to encapsulate fields.Encapsulation promotes safe, modular, and maintainable code by restricting direct access to internal data. It is a cornerstone of robust software design.