Java Encapsulation: Accessors, Mutators, private Methods and final Fields
Why Java classes hide their fields behind methods: the benefits of accessors and mutators, the danger of returning mutable objects (and defensive copies), class-based access to private data, private helper methods, and final instance fields, including final references to mutable objects.
kvi5hnuCode Sprout team member10 min readOn this page
The Employee class from the previous article has private fields and public methods. This article explains why that's the right design, which mistakes can still break encapsulation, and two more tools for well-designed classes: private methods and final fields.
The Benefits of Encapsulation
Look at the simplest methods of Employee:
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
public LocalDate getStartDate() {
return startDate;
}
Each of these does nothing but hand back the current value of one field. Methods like that are called getters (or field accessors).
Wouldn't it be simpler to make name, salary and startDate public? Using methods gives you control and safety.
Only the class can change the data. The salary field is changed only by giveRaise. If the salary ever turns out wrong, only that one method needs to be debugged. With a public field, the culprit could be anywhere in the program.
When you do want outside code to read and change a value, you provide three things:
- a private instance field,
- a public field accessor (getter), and
- a public field mutator (setter).
That's more typing than one public field, but there are considerable benefits:
1. You can change the internal representation without affecting any code outside the class. Suppose name is split into two fields:
private String firstName;
private String lastName;
public String getName() {
return firstName + " " + lastName;
}
Every caller of getName keeps working, unaware of the change. (The accessor and mutator might need to convert between representations, but that work stays inside the class.)
2. Mutators can check for errors. Code that assigns directly to a field can't be forced to check anything. A mutator can enforce the class's rules:
public void setSalary(double salary) {
if (salary < 0) {
throw new IllegalArgumentException("Salary can't be negative: " + salary);
}
this.salary = salary;
}
Rules that must always hold for an object (like "salary is never negative") are called class invariants. Encapsulation is what lets a class guarantee them.
Don't Return References to Mutable Objects
Encapsulation can be broken in a subtle way: by an accessor that returns a reference to a mutable object stored in a field.
Suppose Employee stored its start date as a legacy java.util.Date:
class Employee {
private Date startDate;
...
public Date getStartDate() {
return startDate; // BAD
}
}
Unlike LocalDate, which has no mutator methods, Date has a mutator: setTime, which sets its number of milliseconds. Now consider this rogue code:
Employee omar = ...;
Date d = omar.getStartDate();
double tenYearsInMilliseconds = 10 * 365.25 * 24 * 60 * 60 * 1000;
d.setTime(d.getTime() - (long) tenYearsInMilliseconds);
// let's give Omar ten years of added seniority

d and omar.startDate refer to the same object. Calling a mutator through d changes the private state of the Employee, without any Employee method being involved.
Two fixes:
- Prefer immutable types for fields:
LocalDateinstead ofDate,Stringinstead ofStringBuilder, immutable lists (List.of,List.copyOf) instead of modifiable ones. Then there's nothing to protect. - When a field must be mutable, return a defensive copy, and copy incoming mutable arguments in the constructor too, because the caller may still hold a reference to the object they passed in:
public Employee(String name, Date startDate) {
this.startDate = new Date(startDate.getTime()); // copy in
}
public Date getStartDate() {
return new Date(startDate.getTime()); // copy out
}
(The interfaces part shows a general way to copy objects with clone.)
import java.util.Date;
public class Solution {
public static void main(String[] args) {
LeakyEmployee omar = new LeakyEmployee(new Date(0));
Date d = omar.getStartDate();
d.setTime(d.getTime() - 10L * 365 * 24 * 60 * 60 * 1000);
System.out.println(omar.getStartDate().getTime()); // omar's state changed!
SafeEmployee sally = new SafeEmployee(new Date(0));
Date d2 = sally.getStartDate();
d2.setTime(123);
System.out.println(sally.getStartDate().getTime()); // unchanged
}
}
class LeakyEmployee {
private final Date startDate;
LeakyEmployee(Date startDate) {
this.startDate = startDate;
}
public Date getStartDate() {
return startDate; // BAD: leaks a mutable object
}
}
class SafeEmployee {
private final Date startDate;
SafeEmployee(Date startDate) {
this.startDate = new Date(startDate.getTime()); // defensive copy in
}
public Date getStartDate() {
return new Date(startDate.getTime()); // defensive copy out
}
}
-315360000000
0
Class-Based Access Privileges
Inside an instance method you can obviously read the private fields of this. Less obvious: you can also read the private fields of any other object of the same class that you have a reference to:
class Employee {
...
public boolean sameName(Employee other) {
return name.equals(other.name); // other.name is private, but this is legal
}
}
In a call such as omar.sameName(boss), the method accesses omar's private name (no surprise) and also boss's. That's legal because boss is an Employee, and access control in Java is per class, not per object: code in the Employee class may access private members of any Employee object. (C++ has the same rule.)
This is what makes methods like equals, compareTo and copy constructors straightforward to write.
Private Methods
Fields should be private because public data is dangerous. Most methods are public, but private methods are useful too. When a computation gets long, you split it into helper methods. Such helpers usually shouldn't be part of the public interface: they may depend closely on the current implementation, or need to be called in a particular order or under special conditions.
To make a method private, just use private instead of public:
public double getMonthlySalary() {
return round2(salary / 12);
}
private static double round2(double x) {
return Math.round(x * 100) / 100.0;
}
The big advantage: you're free to change or remove a private method at any time. If the data representation changes and the helper becomes unnecessary or harder to implement, you can simply drop it, because no code outside the class can be using it. A public method is a commitment: other code may rely on it, so you can't just remove it.
Final Instance Fields
You can declare an instance field final. Such a field must be initialized when the object is constructed: by the end of every constructor, the field must have a value. After that, it can never be changed.
For example, an employee's name never changes after construction (there's no setName), so it can be final:
class Employee {
private final String name;
...
}
The compiler enforces both rules:
class F {
private final int x;
F(boolean b) { if (b) x = 1; } // error: variable x might not have been initialized
}
class G {
private final int x = 1;
void m() { x = 2; } // error: cannot assign a value to final variable x
}
final is especially valuable for fields of primitive or immutable types (String, LocalDate, Integer…). Such fields, and objects whose fields are all like that, are guaranteed never to change. (A class is immutable if none of its methods change its objects after construction. String is the classic example.)
final and mutable objects
For fields of mutable types, final can be confusing. Consider:
private final StringBuilder evaluations;
initialized in the constructor with evaluations = new StringBuilder();. The keyword final only means that evaluations will never refer to a different StringBuilder. The StringBuilder object itself can still change:
public void giveGoldStar() {
evaluations.append(LocalDate.now() + ": Gold star!\n"); // perfectly legal
}

final makes the reference constant, not the object. To get a truly unchangeable field, combine final with an immutable type.
A final field may also be null, for example name = (n == null || n.isEmpty()) ? null : n;, but then it stays null forever.
Common questions
Should I generate getters and setters for every field?
No. Add accessors only for the data that callers really need, and add setters only when changing the value makes sense on its own. Prefer methods that express an operation (deposit, rename) and check rules. For plain data carriers, use a record.
Is a public final field acceptable?
For a static constant of an immutable type, yes: public static final int MAX_USERS = 100;. For instance fields, a final field still exposes your internal representation, so you can never change it without breaking callers. Records are the modern way to get "public immutable data" with accessor methods.
How do I return a list field without breaking encapsulation?
Return an unmodifiable view or a copy: return Collections.unmodifiableList(items); or return List.copyOf(items);. Store your own copy in the constructor as well (this.items = new ArrayList<>(items)), so the caller can't change the list after passing it in.
Can one object access another object's private fields?
Yes, if both are of the same class. Java access control is per class, not per object. That is why equals(Object o) can compare this.name with other.name directly after casting.
Do final fields make my class thread-safe?
They help. The Java Memory Model guarantees that other threads see the correct values of final fields once the constructor has finished, as long as this doesn't escape during construction. A class whose fields are all final and of immutable types is thread-safe. Mutable objects behind final references still need synchronisation.
Summary
- Keep fields
private. Accessors read state, mutators change it. Together they let you change the internal representation freely and validate every change (enforcing class invariants). - Don't generate getters and setters blindly. Expose meaningful operations and only the access that's needed.
- Never return (or store) references to mutable objects from outside without copying. Prefer immutable types such as
LocalDate; otherwise make defensive copies. - Access control is per class: a method can access private fields of any object of its own class.
- Use private methods for helpers. They can be changed or removed at any time.
finalfields must be set by the end of every constructor and can't be reassigned. With mutable types,finalfixes only the reference, not the object's contents.
Practice Questions
Name two concrete advantages of a private field with getter/setter over a public field.
(1) The class can change its internal representation without affecting callers; (2) the setter can validate values (and the class can log, notify, or compute derived data), so invariants can't be violated from outside. A third: you can see and debug every place the field changes.
A class stores private int[] scores and has public int[] getScores() { return scores; }. What's the risk, and how do you fix it?
Callers get a reference to the internal array and can modify its elements, changing the object's private state. Return a copy (return scores.clone(); or Arrays.copyOf(scores, scores.length)), and copy the array passed to the constructor too.
Is this legal inside class Point: public double distance(Point other) { return Math.hypot(x - other.x, y - other.y); }, where x and y are private?
Yes. Access control is class-based: methods of Point can access the private fields of any Point object, including other.
private final List<String> tags = new ArrayList<>(); Can tags.add("java") be called later? Can tags = new ArrayList<>(); ?
tags.add("java") is allowed: final doesn't make the list immutable. tags = new ArrayList<>(); is a compile error: a final field can't be reassigned.
Why is it safe to make a helper method private but risky to later remove a public one?
No code outside the class can call a private method, so you can change or delete it without breaking anything else. A public method may be used anywhere (even by other projects), so removing or changing it can break that code.
Previous: Defining Your Own Classes in Java: Fields, Constructors and Methods
Next: Java static Fields and Methods: Class Variables, Constants, Factory Methods and main
Related reading
- Defining Your Own Classes in Java: Fields, Constructors and Methods
- Using Predefined Classes in Java: Objects, Object Variables and LocalDate
- Introduction to Object-Oriented Programming in Java
- Java Arrays: Sorting, the Arrays Class, Multidimensional and Ragged Arrays
- Java Arrays: Declaring, Initializing, for-each Loops and Copying

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.