[!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!