Encapsulation is the OOP mechanism of binding data variables and methods together into a protective capsule, restricting direct unauthorized access from external classes. It is often referred to as Data Hiding.
If class fields are declared public, any external code can tamper with the internal state without validation:
// Unsafe Design (No Encapsulation):
class BadBankAccount {
public double balance; // Anyone can corrupt this!
}
// In main():
BadBankAccount acc = new BadBankAccount();
acc.balance = -99999999.0; // DISASTER: Negative balance allowed!
public class BankAccount {
// 1. Private fields (Hidden from external direct access)
private String accountNumber;
private double balance;
// 2. Constructor
public BankAccount(String accNum, double initialDeposit) {
this.accountNumber = accNum;
setBalance(initialDeposit); // Uses setter validation!
}
// 3. Getter Method (Read access)
public double getBalance() {
return this.balance;
}
// 4. Setter Method (Controlled write access with business validation)
public void setBalance(double amount) {
if (amount < 0) {
System.err.println("Error: Account balance cannot be negative!");
return;
}
this.balance = amount;
}
public String getAccountNumber() {
return this.accountNumber;
}
}
Exam Question: "What are the rules for defining a standard JavaBean class in Java?"
The 4 Official JavaBean Conventions:
1. Must have a public no-argument default constructor.
2. All properties/fields must be private.
3. Must provide standard public getter and setter methods following camelCase conventions.
4. Should implement java.io.Serializable for network or disk persistence.
Now let us examine the 4 access modifiers that govern encapsulation and package visibility. Proceed to: Java Access Modifiers →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Private, protected, and public scopes.
Modern immutable data carriers.
Encapsulation overview.
State and behavior encapsulation.