What is Encapsulation in Java?
Encapsulation in Java
So far, every field you have written has been freely accessible from outside the class. In the real world, that is rarely how trustworthy systems work; you cannot walk into a bank and directly edit your balance on their server. Encapsulation is the OOP principle that enforces this same kind of protection inside your code.
What is Encapsulation?
Encapsulation means bundling an object's data together with the methods that operate on that data, while restricting direct outside access to the data itself. Instead of letting other code reach in and change a field directly, you expose controlled methods that decide what changes are allowed.
Think back to the car analogy from Chapter 1. You do not directly rewire a car's engine to make it go faster; you press the accelerator pedal, a controlled interface, and the engine internals respond appropriately. Encapsulation gives your classes the same kind of safe, controlled interface.
Private Fields and Public Getters/Setters
In practice, encapsulation in Java almost always follows the same recipe: mark fields private so they cannot be accessed directly from outside the class, then provide public getter methods to read them and public setter methods to update them, validating input along the way if needed.
public class BankAccount {
private double balance; // hidden from outside code
public BankAccount(double initialBalance) {
if (initialBalance >= 0) {
balance = initialBalance;
}
}
// Getter — read access
public double getBalance() {
return balance;
}
// Setter — controlled write access
public void deposit(double amount) {
if (amount > 0) {
balance = balance + amount;
}
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance = balance - amount;
} else {
System.out.println("Withdrawal denied: insufficient funds");
}
}
}
Outside code can never write account.balance = -500 directly, because balance is private. It must go through deposit() or withdraw(), and those methods can refuse invalid requests, like a negative deposit or an overdraft, before any damage is done.
Benefits of Encapsulation
Benefit | Why It Matters |
Data protection | Private fields cannot be corrupted or set to invalid values from outside the class |
Validation | Setters can check input before accepting it, e.g. rejecting a negative withdrawal |
Flexibility to change internals | You can rewrite how balance is stored or calculated without breaking code that uses getBalance() |
Easier maintenance | Bugs related to a field's value are confined to one class, not scattered across the codebase |
Quick Tip
A common beginner mistake is writing a getter and setter for every single field automatically, without thinking about whether outside code should really be allowed to change it. Not every field needs a setter; if a value should never change after construction (like a Student's date of birth), only provide a getter.










