Encapsulation
Overview
Encapsulation is the OOP principle of hiding an object's internal state (its variables) from the outside world and strictly controlling access to them through public methods.
If you expose a balance variable in a BankAccount class as public, any other developer can write account.balance = -9000;, instantly breaking your application's logic.
By Encapsulating the data, you mark the variables as private (invisible to other classes) and expose public Getter and Setter methods. This allows you to inject validation logic, ensuring that bad data can never enter the object.
Syntax
public class BankAccount {
// 1. Data Hiding: Variables are strictly private
private double balance = 0.0;
// 2. Controlled Access: Public Getter (Read-Only)
public double getBalance() {
return this.balance;
}
// 3. Controlled Modification: Public Setter (Validation!)
public void deposit(double amount) {
if (amount > 0) {
this.balance += amount; // Safe state change
} else {
System.out.println("Error: Cannot deposit negative amounts!");
}
}
}
public class Main {
public static void main(String[] args) {
BankAccount acc = new BankAccount();
// acc.balance = 5000; // ERROR! balance is private
acc.deposit(5000); // Valid! Passes through validation
System.out.println("Balance: $" + acc.getBalance());
}
}Common Pitfalls
- Blindly auto-generating Getters and Setters for every single variable. If a variable is never meant to be changed after initialization (like a unique ID), do NOT generate a Setter for it! Only expose what is absolutely necessary.
- Returning mutable objects in Getters. If you have
private Date birthDate, and your getter returns it directly, outside code can modify that Date object, breaking encapsulation! Always return a cloned copy of mutable objects.
Interview Questions
A POJO (Plain Old Java Object) is a standard class not bound by framework restrictions. A 'Java Bean' is a strictly encapsulated POJO that follows specific conventions: All variables are private, it has public Getters and Setters for everything, and it features a no-argument default constructor.
Data Hiding is the physical restriction of access using the private modifier. Encapsulation is the broader architectural concept of bundling the hidden data with the specific methods that operate on it, acting as a protective shield.
Real-World Example
In an enterprise application, you often have a User class. The password hash is stored as a private variable. There is NO public getter for the password, meaning it is impossible for UI code to accidentally leak the password to the screen. It can only be accessed internally for validation.
public class User {
private String passwordHash;
// No getPassword() method exists!
public boolean verifyPassword(String input) {
return hashFunc(input).equals(passwordHash);
}
}Check Your Knowledge
Test your understanding of Encapsulation with these quick questions.