Encapsulation
Data hiding and access control
Encapsulation
Encapsulation bundles data (attributes) and methods that operate on that data into a single unit (class), while restricting direct access to some components. It protects internal state from unauthorized access and modification.
java
// Encapsulation with Getters/Setters
public class BankAccount {
// Private fields — hidden from outside
private String accountNumber;
private double balance;
private String owner;
public BankAccount(String accountNumber, String owner, double initialBalance) {
this.accountNumber = accountNumber;
this.owner = owner;
this.balance = initialBalance;
}
// Public getter — controlled read access
public double getBalance() {
return balance;
}
// Public method — controlled write with validation
public void deposit(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException("Deposit must be positive");
}
balance += amount;
}
public boolean withdraw(double amount) {
if (amount <= 0 || amount > balance) {
return false; // Insufficient funds or invalid amount
}
balance -= amount;
return true;
}
// No setter for accountNumber — immutable after creation
public String getAccountNumber() {
return accountNumber;
}
}- private: Accessible only within the same class
- protected: Accessible within the same class, subclasses, and same package
- public: Accessible from anywhere
- default (package-private): Accessible within the same package only
💡
Always make fields private and provide public getters/setters only when necessary. This allows you to add validation, logging, or change the internal representation without breaking external code.