[!NOTE] The first pillar of Object-Oriented Programming is Encapsulation. It is the concept of wrapping data (variables) and code (methods) together as a single unit, and hiding the internal state from the outside world.
Why Hide Data?
Imagine you have a BankAccount class.
If you make the balance variable public, any junior developer writing code anywhere in the application can simply write account.balance = 10000000;. They bypass security checks, fraud detection, and logging entirely.
This is a complete architectural failure.
To achieve Encapsulation, we must:
- Declare all class variables as
private. - Provide
publicGet and Set methods so outside code has to ask permission to alter the data.
public class BankAccount {
// 1. HIDDEN DATA! The outside world cannot touch this.
private double balance = 0.0;
// 2. PUBLIC SETTER. Includes security logic!
public void deposit(double amount) {
if (amount > 0) {
balance = balance + amount;
System.out.println("Deposit valid. Logging transaction...");
} else {
System.out.println("SECURITY ALERT: Invalid negative deposit attempt!");
}
}
// 3. PUBLIC GETTER.
public double getBalance() {
return balance;
}
}
If a developer now runs account.balance = 5;, the compiler will violently error out, refusing to compile the code. They must use your .deposit() method.
The 'this' Keyword
A common problem arises in Constructors and Setters. What if the parameter passed into the method has the exact same name as the class instance variable?
public class Person {
private String name; // Instance variable
// The parameter is also called 'name'!
public Person(String name) {
// DOES NOTHING! It just assigns the parameter to itself.
name = name;
}
}
To solve this naming collision, Java provides the this keyword. this is a reference to the specific physical object currently executing the method.
public class Person {
private String name;
public Person(String name) {
// Translation: Assign the incoming parameter 'name'
// to THIS specific object's instance variable 'name'.
this.name = name;
}
}
[!TIP] Modern IDEs (like IntelliJ or VSCode) have shortcuts to automatically generate Getters, Setters, and Constructors using the
thiskeyword in exactly one second. You will rarely type them manually!
Encapsulation Is More Than Getters and Setters
Encapsulation is about controlling how state changes. A class should expose meaningful actions, not simply allow outside code to edit every field. In a bank account, deposit() and withdraw() are better than a public setBalance().
Prefer Meaningful Methods
class BankAccount {
private double balance;
public void deposit(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException("Amount must be positive");
}
balance += amount;
}
public boolean withdraw(double amount) {
if (amount <= 0 || amount > balance) {
return false;
}
balance -= amount;
return true;
}
public double getBalance() {
return balance;
}
}
Notice there is no public setter for balance. Outside code can ask for valid operations, but it cannot directly corrupt the account.
Using this for Clarity
this is most useful when a parameter has the same name as a field. It tells the reader which value belongs to the current object.
public void rename(String name) {
this.name = name;
}
Common Mistakes
- Generating setters for every field without asking whether the field should be changeable.
- Putting validation in the UI instead of protecting the class itself.
- Returning internal mutable objects directly from getters.
- Using
thiseverywhere when there is no naming conflict or clarity benefit.
Mini Practice
Create a Wallet class with private balance. Add addMoney, spendMoney, and getBalance. Prevent negative additions and overspending.
Practice Lab: Secure Wallet
Protect object state using private fields and meaningful methods.
- Create a
Walletclass with private balance. - Add
addMoney(double amount)and reject non-positive input. - Add
spendMoney(double amount)and prevent overspending. - Add
getBalance(), but no publicsetBalance(). - Use
this.balancewhere it improves clarity.
Goal: Design controlled state changes instead of public field access.
Revision Checkpoint
- Encapsulation: Hide fields and expose controlled operations.
privatefields: Prevent direct outside modification.- Getter: Allows controlled reading.
- Setter: Allows controlled writing, often with validation.
this: Refers to the current object instance.
Before the quiz: Decide whether a field really needs a public setter.