After learning Data Hiding and Abstraction, you're ready to understand one of the most important Object-Oriented Programming (OOP) concepts—Encapsulation.
Many beginners think Encapsulation simply means writing getters and setters.
While getters and setters are commonly used, they are not the complete definition of Encapsulation.
Encapsulation is about keeping data and the methods that operate on that data together in one unit while protecting the internal state through controlled access.
In this article, we'll learn what Encapsulation is, how Java implements it, why JavaBeans follow this pattern, and the interview questions you should know.
What is Encapsulation?
Encapsulation is the process of binding data and the methods that operate on that data into a single unit.
In Java, that single unit is a class.
In simple words:
Binding data and corresponding methods into a single unit is called Encapsulation.
If a Java class follows both:
- Data Hiding (private fields)
- Abstraction (public services)
then it is called an Encapsulated Class.
The Golden Formula
One of the easiest ways to remember Encapsulation is:
Encapsulation = Data Hiding + Abstraction
This is one of the most frequently asked interview and exam questions.
Why Do We Need Encapsulation?
Imagine a bank account.
The account contains important information such as:
- Account holder name
- Account number
- Balance
Should users modify these values directly?
Definitely not.
Instead, the bank provides services such as:
- Deposit
- Withdraw
- Check Balance
These services ensure that business rules are followed before updating the data.
Encapsulation allows the class to protect its internal data while exposing only the required operations.
| Without Encapsulation | With Encapsulation |
|---|---|
| Data is directly accessible | Data is protected |
| No validation | Validation is possible |
| Difficult to maintain | Easy to maintain |
| Poor security | Better security |
| Tightly coupled | Better modularity |
Real-World Analogy
Think about an ATM.
You cannot directly change your account balance.
Instead, you request services such as:
- Withdraw
- Deposit
- Balance Enquiry
The ATM internally validates your PIN, checks your balance, updates the database, and logs the transaction.
You only see the service.
The data and implementation remain protected.
This is Encapsulation.
How Does Java Implement Encapsulation?
A class is considered encapsulated when:
- All instance variables are declared
private. - Public methods provide controlled access to those variables.
This is the standard Java approach.
The Recipe for Encapsulation
Step 1
↓
Declare every data member private.
↓
Step 2
↓
Provide public getter methods.
↓
Step 3
↓
Provide public setter methods (if modification is allowed).
↓
Encapsulated Class
Basic Example
class Account {
private double balance;
private String accountHolder;
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
if (balance >= 0) {
this.balance = balance;
}
}
public String getAccountHolder() {
return accountHolder;
}
public void setAccountHolder(String accountHolder) {
this.accountHolder = accountHolder;
}
}
How It Works
Step 1
The variables are declared private.
External classes cannot access them directly.
Step 2
The getter methods expose the values in a controlled way.
Step 3
The setter methods validate incoming data before updating the object.
Step 4
The object always remains in a valid state.
Rules
Rule 1: Declare Data Members as Private
class Employee {
private double salary;
}
Step-by-Step Explanation
Step 1
The field is declared private.
Step 2
Only the Employee class can access it directly.
Step 3
External classes cannot modify it.
Step 4
This achieves Data Hiding.
Rule 2: Provide Public Getter Methods
Getter methods allow controlled reading of data.
class Employee {
private double salary = 75000;
public double getSalary() {
return salary;
}
}
Output
75000.0
Step-by-Step Explanation
Step 1
The salary remains hidden.
Step 2
The getter method exposes the value.
Step 3
Clients call the getter instead of accessing the field directly.
Step 4
The class retains control over how data is exposed.
Rule 3: Provide Public Setter Methods
Setter methods allow controlled updates.
class Employee {
private double salary;
public void setSalary(double salary) {
if (salary >= 0) {
this.salary = salary;
}
}
}
Step-by-Step Explanation
Step 1
The method receives the new value.
Step 2
Validation is performed.
Step 3
Only valid values are stored.
Step 4
Invalid object states are prevented.
Rule 4: Validation Belongs Inside the Class
One of the biggest advantages of Encapsulation is that business rules remain inside the class.
class Account {
private double balance;
public void setBalance(double balance) {
if (balance < 0) {
throw new IllegalArgumentException("Balance cannot be negative.");
}
this.balance = balance;
}
}
The caller doesn't need to know how validation works.
Practical Examples
Beginner Example
class Student {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Business Example
class Product {
private double price;
public double getPrice() {
return price;
}
public void setPrice(double price) {
if (price > 0) {
this.price = price;
}
}
}
Interview Example
class BankAccount {
private double balance;
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
}
Notice that there is no setter for balance. Clients can increase the balance only through the deposit() method, which enforces business rules. This is a stronger example of Encapsulation than exposing a public setBalance() method.
JavaBean Standard
A JavaBean is a simple Java class that follows the principles of Encapsulation.
A JavaBean typically has:
- Private fields
- Public getters
- Public setters
- A public no-argument constructor (commonly expected by many frameworks)
Setter Method Rules
| Rule | Description |
|---|---|
| Method name | Starts with set
|
| Access modifier | public |
| Return type | void |
| Parameters | Exactly one parameter |
Example:
public void setName(String name)
Getter Method Rules
| Rule | Description |
|---|---|
| Method name | Starts with get
|
| Access modifier | public |
| Return type | Must return the property type |
| Parameters | No parameters |
Example:
public String getName()
Boolean Getter Rule
Boolean properties commonly use the is prefix.
class Student {
private boolean active;
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
}
Although getActive() is allowed in many contexts, isActive() is the conventional and recommended naming for boolean properties.
Visual Explanation
Encapsulated Class
+-----------------------------+
| private Data Members |
| |
| public Getter Methods |
| public Setter Methods |
| Validation |
| Business Rules |
+-------------+---------------+
▲
│
Outside World
The outside world communicates only through the public methods.
Data Hiding vs Abstraction vs Encapsulation
| Concept | What is Hidden? | Implemented Using |
|---|---|---|
| Data Hiding | Internal data |
private access modifier |
| Abstraction | Internal implementation | Abstract classes and interfaces |
| Encapsulation | Combines data and methods while hiding data and exposing controlled services | Private fields with public methods |
Quick Way to Remember
- Data Hiding → Hide Data
- Abstraction → Hide Implementation
- Encapsulation → Combine Both
Common Beginner Mistakes
Mistake 1: Declaring Fields as Public
❌ Incorrect
class Account {
public double balance;
}
Why?
Anyone can modify the value without validation.
✅ Correct
class Account {
private double balance;
}
Mistake 2: Exposing Unnecessary Setters
Not every field should have a setter.
For example, a transaction ID should usually be read-only after creation.
class Transaction {
private final String transactionId;
public Transaction(String transactionId) {
this.transactionId = transactionId;
}
public String getTransactionId() {
return transactionId;
}
}
Mistake 3: Performing Validation Outside the Class
Validation should be the responsibility of the encapsulated class.
Don't rely on callers to provide valid data.
Interview Questions
1. What is Encapsulation?
Why interviewers ask this
To verify your understanding of one of the four OOP pillars.
Expected answer
Encapsulation is the process of binding data and the methods that operate on that data into a single unit while protecting the data through controlled access.
Common trap
Answering only "Encapsulation means getters and setters." Getters and setters are a common implementation technique, not the definition itself.
2. What is the formula for Encapsulation?
Expected answer
Encapsulation = Data Hiding + Abstraction
3. How do you implement Encapsulation in Java?
Expected answer
Declare fields as private and provide controlled access through public methods such as getters, setters, or domain-specific operations.
4. What are the advantages of Encapsulation?
Expected answer
- Better security
- Controlled access
- Improved maintainability
- Better modularity
- Easier enhancement
- Greater flexibility
5. What are the disadvantages of Encapsulation?
Expected answer
Encapsulation may increase code size because additional methods are required. Method calls introduce a very small overhead compared to direct field access. In modern JVMs, this overhead is often minimized through compiler and JIT optimizations, so the benefits usually outweigh the cost.
Best Practices
- Declare instance variables as
private. - Expose only the operations that clients actually need.
- Avoid creating setters for immutable or read-only fields.
- Perform validation inside setter or business methods.
- Prefer business methods such as
deposit()orwithdraw()over generic setters for important state. - Follow JavaBean naming conventions where appropriate.
- Keep business rules inside the class.
Performance Notes
Getter and setter methods add a small method-call overhead compared to direct field access. However, modern JVMs frequently inline simple methods during JIT compilation, making the performance impact negligible in most applications. The benefits of security, maintainability, and flexibility almost always outweigh this cost.
Quick Memory Trick 🧠
Think of a capsule medicine.
Capsule
↓
Medicine (Data)
↓
Capsule Shell (Methods)
↓
Safe Delivery
The medicine is protected inside the capsule.
Similarly:
- Data stays protected.
- Methods provide controlled access.
- Together, they form Encapsulation.
FAQ
Is Encapsulation the same as Data Hiding?
No. Data Hiding protects internal data, while Encapsulation combines data and behavior into a single unit and typically uses Data Hiding to protect that data.
Is Encapsulation possible without getters and setters?
Yes. A class can expose domain-specific methods like deposit() and withdraw() instead of generic setters. In many designs, this is preferred.
Does every field need a setter?
No. Read-only or immutable fields often expose only getters or no accessor methods at all.
What is a JavaBean?
A JavaBean is a Java class that typically contains private properties, public getters and setters, and follows standard naming conventions.
Why is Encapsulation important?
It protects object state, enforces business rules, improves maintainability, and reduces coupling between different parts of an application.
Key Takeaways
- Encapsulation binds data and methods into a single unit.
- An encapsulated class combines Data Hiding and Abstraction.
- The commonly remembered formula is Encapsulation = Data Hiding + Abstraction.
- Declare fields as
privateand expose only controlled operations. - JavaBeans are a common implementation of Encapsulation.
- Not every field should have a setter—expose behavior rather than unrestricted state changes.
- Encapsulation improves security, maintainability, flexibility, and modularity.
- The small performance overhead of method calls is generally negligible on modern JVMs.
If you found this guide helpful, leave a ❤️ and follow for more beginner-friendly Java tutorials, interview questions, and practical coding examples.
Happy Coding!
Top comments (0)