When writing Java code, it’s easy to focus on making a program work. But good object-oriented design is also about controlling how that program can be used.
That’s where encapsulation and visibility come in.
What Is Encapsulation?
Encapsulation means protecting an object’s internal state and providing controlled ways to interact with it.
Instead of allowing other classes to change a field directly, we can make it private and expose methods that enforce the object’s rules.
public class BankAccount {
// Private state: cannot be changed directly from outside the class.
private double balance;
public BankAccount(double initialBalance) {
if (initialBalance < 0) {
throw new IllegalArgumentException("Balance cannot be negative");
}
this.balance = initialBalance;
}
// Public API: exposes only the information callers need.
public double getBalance() {
return balance;
}
// Public behavior: validates changes and protects the object's rules.
public void deposit(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException("Deposit must be positive");
}
balance += amount;
}
public void withdraw(double amount) {
if (amount <= 0 || amount > balance) {
throw new IllegalArgumentException("Invalid withdrawal");
}
balance -= amount;
}
// Package-private: available only to classes in the same package.
void applyMonthlyFee(double fee) {
if (fee < 0 || fee > balance) {
throw new IllegalArgumentException("Invalid fee");
}
balance -= fee;
}
// Protected: available to subclasses and classes in the same package.
protected boolean hasMinimumBalance(double minimum) {
return balance >= minimum;
}
// Private: internal implementation detail.
private void resetBalance() {
balance = 0;
}
}
Top comments (0)