Module 5: Classes, Objects, and Constructors
Encapsulation and Getters/Setters
Protect object state by hiding fields and exposing controlled access through methods.
Author
Java Learner Editorial Team
Reviewer
Technical review by Java Learner
Last reviewed
2026-04-16
Java version
Java 25 LTS
Learning goals
- Understand why fields are often `private`
- Use getters and setters for controlled access
- Add simple validation before changing object state
Encapsulation means bundling data and behavior together while controlling access: It helps keep objects in valid states.
Private fields hide raw internals from other classes: Outside code must go through methods you define.
Getters read values and setters update values carefully: Setters are useful because they can validate input before changing the field.
Why this matters: Encapsulation keeps the object in charge of its own rules.
Runnable examples
A setter can reject invalid data
class BankAccount {
private double balance;
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.deposit(50);
System.out.println(account.getBalance());
}
}Expected output
50.0
Common mistakes
Leaving all fields public and changing them freely from anywhere
Use private fields when the object should enforce rules about its own data.
Mini exercise
Create a `Student` class with a private `grade` field and a setter that accepts only values from 0 to 100.
Summary
- Encapsulation protects object state.
- Private fields reduce accidental misuse.
- Getters and setters create controlled access.
Next step
The next module teaches inheritance and polymorphism so related classes can share behavior cleanly.
Sources used