Encapsulation with
Getters & Setters
Learn how private fields protect your data and how getter/setter methods provide controlled access in Java.
What Is Encapsulation?
Encapsulation is one of the four pillars of Object-Oriented Programming. It means bundling data (fields) and behavior (methods) together inside a class, while hiding the internal details from outside code.
Why Does It Matter?
The Problem Without Encapsulation
The Core Rule of Encapsulation
Access Modifiers: Quick Refresher
| Modifier | Same Class | Same Package | Subclass | World |
|---|---|---|---|---|
| public | ✓ | ✓ | ✓ | ✓ |
| protected | ✓ | ✓ | ✓ | ✕ |
| (default) | ✓ | ✓ | ✕ | ✕ |
| private | ✓ | ✕ | ✕ | ✕ |
public vs private Fields
Anatomy of a Getter
Anatomy of a Setter
How to Encapsulate a Class
Example 1: BankAccount
Example 2: Temperature Conversion
Example 3: Rectangle with Validation
The this Keyword
When the parameter name and the field name are the same, Java needs a way to tell them apart. this always refers to the current object's field.
Common Mistakes to Avoid
Summary Comparison
| Aspect | Getter | Setter |
|---|---|---|
| Purpose | Read a field's value | Modify a field's value |
| Return type | Matches field type | void |
| Parameters | None | One (same type as field) |
| Naming | getX() / isX() | setX() |
| Validation | Not needed | Recommended |
| Can be omitted? | Yes (write-only field) | Yes (read-only field) |
Question 1 of 5
Which access modifier should be used for fields to achieve encapsulation in Java?
Question 2 of 5
What is the return type of a correctly written setter method?
Question 3 of 5
Consider this setter:
public void setScore(int score) {
score = score;
}
What is wrong with the setter shown above?
Question 4 of 5
If a class has a private field called active of type boolean, what should the getter method be named following Java conventions?
Question 5 of 5
A BankAccount class has a private balance field with a getter but no setter. How should the balance be changed?