Encapsulation in Java: A Comprehensive Guide with Practical Example
What is Encapsulation in Java?
Encapsulation is one of the core pillars of object‑oriented design in Java. It bundles data (fields) and the operations that manipulate that data (methods) into a single, self‑contained unit—the class. By hiding the internal state behind a well‑defined interface, encapsulation protects objects from unintended interference and makes code easier to maintain and test.
In this tutorial you will learn:
- What encapsulation is and why it matters
- How to implement encapsulation with a practical example
- Data hiding in Java
- Getter and setter methods (accessors and mutators)
- Abstraction vs. encapsulation
- Key advantages of encapsulation in Java applications
Click here if the video is not accessible
Learn Encapsulation with an Example
To illustrate encapsulation, consider a simple bank‑account class that offers deposit and balance‑display functionality.
class Account {
private int accountNumber;
private int accountBalance;
public void showData() {
// code to display data
}
public void deposit(int amount) {
if (amount < 0) {
// show error
} else {
accountBalance = accountBalance + amount;
}
}
}
Imagine a malicious actor has access to the source code and attempts to inject a negative deposit of -100. There are two common attack vectors:
Approach 1: Directly modifying the accountBalance field. Because the field is declared private, it is inaccessible from outside the Account class, preventing this attack.

As you can see, the private modifier enforces encapsulation and shields the internal state.

Therefore the hacker cannot tamper with the balance directly.

Approach 2: Using the public deposit method to add a negative amount. The method contains a validation check that rejects any amount less than zero, thwarting this attempt as well.

Thus, encapsulation ensures that only legitimate operations can modify the object’s state.

The entire class behaves like a sealed capsule—data is hidden, and interaction occurs solely through well‑defined messages. This is the essence of encapsulation.

Data Hiding in Java
Data hiding is the practice of restricting direct access to an object's fields from outside its defining class. In Java, the private keyword enforces this restriction, making the field invisible to all other classes. This keeps the internal representation opaque, allowing developers to modify it without breaking dependent code.
Sometimes a less restrictive access level, such as protected or public, is required for inheritance or utility classes. However, encapsulation encourages using private fields coupled with controlled accessor methods.
Getter and Setter Methods in Java
Getters (accessors) and setters (mutators) provide a controlled interface for reading and updating private fields. They enable validation, logging, or lazy initialization while preserving encapsulation.
Example:
class Account {
private int accountNumber;
private int accountBalance;
// accessor
public int getBalance() {
return this.accountBalance;
}
// mutator
public void setNumber(int num) {
this.accountNumber = num;
}
}
Here, getBalance() returns the current balance, while setNumber() assigns a new account number.
Abstraction vs. Encapsulation
Although related, abstraction and encapsulation serve distinct purposes:
- Encapsulation: Focuses on “how” a class hides its internal state and exposes behavior.
- Abstraction: Focuses on “what” a class can do, presenting only the essential operations to the user.
Think of a smartphone: the complex circuitry is encapsulated behind a touch interface, while abstraction provides the high‑level functions such as dialing or texting.
Advantages of Encapsulation in Java
- Groups related data and behavior into cohesive classes.
- Enhances security by restricting direct field access.
- Facilitates unit testing because the internal state is protected.
- Allows internal implementation to change without affecting external code, boosting maintainability.
- Encourages clear APIs through getters and setters, improving readability and documentation.
Java
- Mastering Java Encapsulation: A Practical Guide to Data Hiding
- Java Variables and Data Types – A Comprehensive Guide with Examples
- Understanding Java Classes and Objects: Clear Concepts, Practical Examples
- Understanding Java String.charAt(): Syntax, Return Type, Exceptions, and a Practical Example
- Mastering Java’s String.endsWith(): How to Check String Suffixes with Examples
- Java HashMap: A Comprehensive Guide
- Command‑Line Arguments in Java: A Practical Guide with Code Examples
- Java Inheritance Explained: Types, Syntax, and Practical Examples
- Polymorphism in Java: A Comprehensive Guide with Practical Examples
- Understanding Java's throws Keyword: Examples & Best Practices