Think about a Tylenol or Advil capsule. Inside the plastic shell is the actual medicine (the data). You don't interact with the powder directly; you just take the capsule. The shell protects the contents from the outside world and ensures you use the medicine exactly how it was intended.
In Java, Encapsulation means:
Hiding the data (variables) by making them
private.Providing access to that data only through "doors" called Getters and Setters.
Why do this?
If I have a BankEmployee class with a balance variable, I don't want anyone to just type account.balance = 1000000;. By making it private, I force them to use a method where I can check their identity or verify that the amount is valid before changing it.
The Access Modifiers
public: Accessible from anywhere in your project.private: Accessible only inside that specific class. No one else can see it.
The Code Example:
class BankAccount {
// 1. Private variables (Hidden from the outside)
private String accountHolder;
private double balance;
// 2. Constructor
public BankAccount(String name, double startingBalance) {
this.accountHolder = name;
this.balance = startingBalance;
}
// 3. Getter Method (The "Viewing Window")
public double getBalance() {
return balance;
}
// 4. Setter Method (The "Controlled Door")
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Successfully deposited $" + amount);
} else {
System.out.println("Invalid amount! You can't deposit negative money.");
}
}
}
public class Main {
public static void main(String[] args) {
BankAccount myAccount = new BankAccount("John Doe", 500.00);
// This would cause a COMPILE ERROR:
// myAccount.balance = 5000;
// We must use the public methods
myAccount.deposit(150.00);
myAccount.deposit(-50.00); // This will trigger the safety check
System.out.println("Final Balance: $" + myAccount.getBalance());
}
}Expected Output:
Successfully deposited $150.0
Invalid amount! You can't deposit negative money.
Final Balance: $650.0