01 / 21

Encapsulation with
Getters & Setters

Learn how private fields protect your data and how getter/setter methods provide controlled access in Java.

Java OOP

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?

Data Protection
Prevents outside code from setting invalid values, like a negative age or a null name.
Flexibility
You can change how data is stored internally without breaking code that uses the class.
Maintainability
Bugs are easier to find because only getter/setter methods can modify each field.

The Problem Without Encapsulation

public class Student { public String name; public int age; } // Anywhere in your program: Student s = new Student(); s.age = -5; // No error! Age is now invalid. s.name = null; // No protection at all.

The Core Rule of Encapsulation

Student private String name private int age public getName() / setName() public getAge() / setAge() Outside Code ✕ Blocked ✓ Allowed ✕ ✕

Access Modifiers: Quick Refresher

Modifier Same Class Same Package Subclass World
public ✓✓✓✓
protected ✓✓✓✕
(default) ✓✓✕✕
private ✓✕✕✕

public vs private Fields

public fields
Accessible from anywhere. No validation, no control. Changed freely by any class.
private fields
Accessible only within the same class. Must go through methods to read/write. Full control.

Anatomy of a Getter

public String getName() { return this.name; }
1
Return type matches the field type (String, int, etc.).
2
Naming convention: get + field name with first letter capitalized. For boolean fields, use is instead of get.
3
No parameters: a getter simply returns the current value.

Anatomy of a Setter

public void setAge(int age) { if (age >= 0 && age <= 150) { this.age = age; } }
1
Return type is void: a setter does not return anything.
2
Takes one parameter whose type matches the field.
3
Validation logic lives here: reject invalid values before they corrupt the field.

How to Encapsulate a Class

1
Declare all fields private: no outside code can touch them directly.
2
Write a getter for every field that outside code needs to read.
3
Write a setter for every field that outside code needs to modify. Add validation inside.
4
Use this to distinguish the field from the parameter when they share the same name.
5
Omit the setter if a field should be read-only after construction.

Example 1: BankAccount

public class BankAccount { private final String owner; // Read-only after construction private double balance; public BankAccount(String owner, double initialBalance) { this.owner = owner; this.balance = Math.max(0, initialBalance); } public String getOwner() { return owner; } public double getBalance() { return balance; } public void deposit(double amount) { if (amount > 0) { this.balance += amount; } } }

Example 2: Temperature Conversion

public class Temperature { private double celsius; public Temperature(double celsius) { this.setCelsius(celsius); // Reuse validation logic } public double getCelsius() { return celsius; } public void setCelsius(double celsius) { if (celsius >= -273.15) { this.celsius = celsius; } } public double getFahrenheit() { return celsius * 9.0 / 5.0 + 32; } }

Example 3: Rectangle with Validation

public class Rectangle { private double width; private double height; public Rectangle(double width, double height) { this.setWidth(width); // Reuse validation this.setHeight(height); // from setters } public double getWidth() { return width; } public double getHeight() { return height; } public void setWidth(double w) { if (w > 0) { this.width = w; } } public void setHeight(double h) { if (h > 0) { this.height = h; } } public double getArea() { return width * height; } }

The this Keyword

public void setName(String name) { this.name = name; // ^field ^parameter }

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.

this.name
The instance variable (field) belonging to the object.
name
The parameter passed into the setter method.

Common Mistakes to Avoid

✕ Public Fields
Declaring fields as public instead of private defeats the entire purpose of encapsulation.
✕ Forgetting this
Writing name = name in a setter assigns the parameter to itself. The field stays unchanged.
✕ Wrong Return Type
A getter for an int field that returns void, or a setter that returns a value instead of void.
✕ No Validation
A setter that blindly assigns without checking: this.age = age; with no bounds check.

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

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?