Encapsulation is one of the fundamental ideas of object-oriented programming in Java. It means keeping an object's internal state protected and providing controlled ways for other code to interact with it. Instead of allowing every part of an application to change an object's data directly, a class can decide how that data should be read or modified.
Encapsulation is closely related to
data hiding,
access control, and
class design.
In Java, the private access modifier is commonly
used to protect fields, while public methods expose only the operations that callers
actually need.
What Is Encapsulation?
Encapsulation means combining related state and behavior inside a class while controlling how the internal state can be accessed.
public class BankAccount {
private double balance;
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
}
The balance field is private, so outside code cannot
modify it directly through normal field access. Instead, the class exposes methods that
control how the balance is read and changed.
This is more than simply hiding a variable. The class can enforce rules whenever the state changes.
Why Encapsulation Matters
Without encapsulation, every class using an object could potentially change its fields directly. As an application grows, this makes it difficult to understand where an object's state is changed and which rules must be followed.
Protects State
Important fields can be hidden from direct external modification.
Enforces Rules
Methods can validate values before changing internal state.
Reduces Coupling
Other classes depend on a public API rather than internal implementation details.
Improves Maintainability
Internal implementation can change without requiring every caller to change.
Encapsulation vs Data Hiding
These terms are closely related but are not exactly the same. Data hiding focuses on restricting direct access to implementation details, while encapsulation is the broader design practice of keeping state and behavior together behind a controlled interface.
For example, making a field private hides direct access to that field.
Providing a public method such as deposit()
then gives callers a controlled way to perform an operation.
Using private Fields
The private modifier limits a member's direct
access to the class that declares it.
This makes it a common starting point for encapsulating object state.
public class User {
private String name;
private int age;
}
Code outside the User class cannot directly write:
User user = new User();
// Not accessible because name is private
user.name = "Alice";
Instead, the class decides which operations should be publicly available.
Getters
A getter is a method that provides access to a value maintained by an object.
A common naming convention is getFieldName().
public class User {
private String name;
public String getName() {
return name;
}
}
External code can read the value through the method:
User user = new User();
System.out.println(user.getName());
A getter is not required for every private field. Sometimes a class should deliberately avoid exposing internal state directly and instead provide higher-level behavior.
Setters
A setter is a method commonly used to change the value of a field.
A typical naming convention is setFieldName().
public class User {
private String name;
public void setName(String name) {
this.name = name;
}
}
The important advantage of a setter is that validation can be placed inside the method.
public void setAge(int age) {
if (age >= 0) {
this.age = age;
}
}
The class can therefore prevent invalid values instead of trusting every caller to perform the validation correctly.
Getters and Setters Are Not the Whole of Encapsulation
A common beginner explanation of encapsulation is "make fields private and create getters and setters." While this is a common pattern, good encapsulation goes further.
Giving every field both a getter and setter may simply move public field access behind methods without providing meaningful control. A better design exposes only the operations that make sense for the object.
public class BankAccount {
private double balance;
public void deposit(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException(
"Deposit must be greater than zero"
);
}
balance += amount;
}
public boolean withdraw(double amount) {
if (amount <= 0 || amount > balance) {
return false;
}
balance -= amount;
return true;
}
public double getBalance() {
return balance;
}
}
There is no setBalance() method.
That is intentional. Allowing callers to set the balance to any arbitrary value
could bypass the rules implemented by deposit and withdrawal operations.
Access Modifiers in Java
Java provides access modifiers that control the visibility of classes, fields,
methods, and constructors. The main access levels are
private,
protected,
public, and
package-private
access when no modifier is specified.
| Modifier | Same Class | Same Package | Subclass in Other Package | Unrelated Other Package |
|---|---|---|---|---|
| private | Yes | No | No | No |
| package-private | Yes | Yes | No | No |
| protected | Yes | Yes | Yes* | No |
| public | Yes | Yes | Yes | Yes |
* Protected access across packages follows Java's specific inheritance rules; it is not unrestricted access to every object instance from the other package.
public Access
The public modifier provides the broadest
normal access level. A public member can be accessed from code that can access
the declaring type.
public class Calculator {
public int add(int a, int b) {
return a + b;
}
}
Public methods are often used as part of the class's external API. They should expose behavior that callers genuinely need.
private Access
The private modifier restricts access to
the declaring class. It is commonly used for internal fields and implementation methods.
public class User {
private String passwordHash;
private boolean isValidPassword(String password) {
return password != null && !password.isBlank();
}
}
Other classes cannot directly access these members. This allows the class to change its internal implementation without making those details part of the external API.
package-private Access
When no access modifier is written, Java gives a member package-private access. Such members are accessible from classes in the same package but not from unrelated classes in other packages.
class InternalService {
void executeInternalTask() {
System.out.println("Internal operation");
}
}
Package-private access is useful when several classes in the same package need to cooperate while the implementation should remain hidden from the rest of the application.
protected Access
The protected modifier allows access from
code in the same package and also provides access to subclasses according to
Java's inheritance rules.
class Vehicle {
protected int speed;
}
class Car extends Vehicle {
public void accelerate() {
speed += 10;
}
}
Protected members are particularly relevant when designing inheritance hierarchies, although private state with protected or public behavior is often preferable when stronger encapsulation is needed.
Access Modifiers and Encapsulation
Access modifiers provide the mechanisms that make encapsulation possible. A class can decide which parts of its implementation are private, which parts can be shared within a package, and which behavior should form part of its public API.
public class Product {
private double price;
private int stock;
public double getPrice() {
return price;
}
public void updateStock(int quantity) {
if (quantity >= 0) {
stock = quantity;
}
}
public boolean isAvailable() {
return stock > 0;
}
}
External code can ask for the price, update stock through a validation method, and check availability without directly manipulating the internal fields.
Immutable Objects
Encapsulation is also useful when designing objects whose state should not change after construction. Such objects are commonly called immutable.
public final class UserProfile {
private final String name;
private final int age;
public UserProfile(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
This class has no setters, and its fields are assigned during construction. Making fields final prevents them from being reassigned after initialization. Immutability can simplify reasoning about object state because the values do not change after the object has been created.
Encapsulation Does Not Mean Hiding Everything
Encapsulation is about controlling access, not making every member private regardless of context. A class should expose the operations that form a useful and understandable API.
For example, an Order class may expose:
order.calculateTotal();
order.addItem(item);
order.removeItem(item);
order.getItemCount();
These methods express meaningful operations instead of exposing every internal collection, calculation, or implementation detail.
Why Direct Field Access Can Be a Problem
Consider a class with public state:
public class BankAccount {
public double balance;
}
Any caller could then write:
account.balance = -100000;
The class has no opportunity to validate the change. With encapsulation, the class controls the operation:
public void withdraw(double amount) {
if (amount <= 0 || amount > balance) {
return;
}
balance -= amount;
}
Now the class owns the rules for changing the account balance.
Encapsulation and Invariants
An invariant is a condition that should remain true for a valid object. Encapsulation helps a class protect such conditions.
For a bank account, a business rule might be that a particular account cannot withdraw more money than its available balance. A properly encapsulated class can ensure that every withdrawal operation respects that rule.
public boolean withdraw(double amount) {
if (amount <= 0 || amount > balance) {
return false;
}
balance -= amount;
return true;
}
Because callers cannot directly change the balance field, they must go through the operations designed by the class.
Encapsulation and Inheritance
Encapsulation becomes particularly important when inheritance is involved. Making fields protected may give subclasses direct access to internal state, but it can also create tighter coupling between the parent and child classes.
class Vehicle {
private int speed;
protected int getSpeed() {
return speed;
}
protected void setSpeed(int speed) {
if (speed >= 0) {
this.speed = speed;
}
}
}
class Car extends Vehicle {
public void accelerate() {
setSpeed(getSpeed() + 10);
}
}
This approach keeps the actual field private while exposing controlled operations to subclasses. The correct choice depends on the design and the responsibilities of the inheritance hierarchy.
Encapsulation and Collections
Encapsulation is especially important when a class internally manages a collection. Returning a mutable internal collection directly can allow callers to bypass the class's rules.
public class Team {
private final List<String> members = new ArrayList<>();
public void addMember(String name) {
if (name != null && !name.isBlank()) {
members.add(name);
}
}
public List<String> getMembers() {
return List.copyOf(members);
}
}
The class controls how members are added, while callers receive a view that does not allow them to modify the internal collection through the returned list.
The broader lesson is important: protecting an object means considering the data reachable through its public methods, not only making the top-level field private.
A Practical BankAccount Example
The following example combines private state, validation, getters, and controlled operations.
public class BankAccount {
private final String accountNumber;
private double balance;
public BankAccount(
String accountNumber,
double initialBalance
) {
if (accountNumber == null || accountNumber.isBlank()) {
throw new IllegalArgumentException(
"Account number is required"
);
}
if (initialBalance < 0) {
throw new IllegalArgumentException(
"Initial balance cannot be negative"
);
}
this.accountNumber = accountNumber;
this.balance = initialBalance;
}
public String getAccountNumber() {
return accountNumber;
}
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException(
"Deposit must be greater than zero"
);
}
balance += amount;
}
public boolean withdraw(double amount) {
if (amount <= 0 || amount > balance) {
return false;
}
balance -= amount;
return true;
}
}
The account number cannot be reassigned, the balance cannot be changed directly, and deposit and withdrawal rules are enforced by the class itself. This is a stronger form of encapsulation than simply providing setters for both fields.
Access Modifiers: When to Use Them
private
Use for implementation details and state that should only be controlled by the declaring class.
package-private
Useful when several types inside the same package need to cooperate without exposing the member outside the package.
protected
Useful in inheritance-oriented designs when subclasses need access under Java's protected visibility rules.
public
Use for behavior and API elements that other parts of the application are intended to call.
Common Encapsulation Mistakes
Making Every Field Public
Public mutable fields allow any caller to change state without going through validation or business rules.
Adding Setters for Everything
A setter is not automatically the correct API for every property. Some state should be changed only through meaningful operations.
Returning Mutable Internal Collections
Returning an internal mutable list or map directly can allow callers to modify state without the class's knowledge.
Exposing Implementation Details
A public API should describe useful operations rather than forcing callers to understand how the class stores or calculates its data.
Using protected Fields by Default
Protected fields expose internal state to subclasses and can increase coupling. Consider private fields with controlled methods where appropriate.
Ignoring Object Invariants
If an object has rules that must remain true, every state-changing operation should respect those rules.
Encapsulation Design Checklist
- Keep internal state private when callers do not need direct access.
- Expose meaningful operations instead of exposing raw implementation details.
- Validate values at the point where state changes.
- Do not create setters automatically for every field.
- Protect mutable collections and other mutable internal objects.
- Use public methods to define a clear external API.
- Use package-private or protected access when the design genuinely requires it.
- Keep object invariants valid after every public state-changing operation.
Encapsulation Flow
External Code
|
v
Public Method
|
v
Validation / Rules
|
v
Private State
|
v
Updated Object State
The important idea is that callers interact with the object's public behavior, while the class remains responsible for protecting and managing its own internal state.
Java Encapsulation: Key Takeaways
- Encapsulation protects an object's internal state through controlled access.
- private is commonly used to hide fields from direct external access.
- Getters can expose values without exposing the field itself.
- Setters can validate and control state changes, but they are not required for every field.
- Meaningful behavior methods can provide stronger encapsulation than generic setters.
- public members form part of a class's external API.
- Package-private members are available within the same package.
- protected access works within the same package and under Java's inheritance rules.
- Encapsulation can protect object invariants and reduce coupling.
- Mutable collections and objects also need to be considered when protecting state.
- Good encapsulation hides unnecessary implementation details while exposing useful behavior.
Summary
Java encapsulation is the practice of protecting an object's internal state and exposing
controlled ways to work with that state. The private
modifier is a key tool for data hiding, while public methods provide the interface through
which other code interacts with the object.
Getters and setters are common patterns, but strong encapsulation is about more than generating methods for every field. A well-designed class exposes meaningful operations, validates state changes, protects its invariants, and keeps implementation details hidden wherever they are not part of the class's public contract.
Access modifiers such as private, protected, package-private, and public give Java developers precise control over visibility. Used together with thoughtful class design, they help create code that is easier to maintain, extend, and reason about.