- 1Java OOP Introduction
- 2Java Class
- 3Java Class Constructor
- 4Java Class Objects
- 5Java Access Modifiers
- 6Java Static Variables in Classes
- 7Java Static Methods Explained
- 8Java Static Blocks
- 9Java final Variables
- 10Java final Methods
- 11Java final class
- 12Inheritance in Java
- 13Java Method Overriding
- 14Java Abstraction in OOP
- 15Interfaces in Java
- 16Polymorphism in Java
- 17Encapsulation in Java
- 18Java Nested Classes
- 19Java Nested Static Class
- 20Java Anonymous Class
- 21Java Singleton Class
- 22Java Enums
- 23Reflection in Java
Encapsulation in Java
Basics and Examples
Encapsulation in Java is a core concept of Object-Oriented Programming (OOP) that allows you to bundle data (variables) and methods (functions) that operate on the data into a single unit: the class. More importantly, it enables data hiding — restricting direct access to class fields from outside code, while still providing controlled access through methods.
Why Encapsulation Matters
Without encapsulation, our classes would be exposed — any part of the codebase could directly modify the internal state of objects. That’s a recipe for unpredictable behavior. Encapsulation ensures:
- Control over how the internal data is accessed or modified.
- Improved security by hiding sensitive fields.
- Cleaner, more maintainable code.
How to Implement Encapsulation in Java
Let’s break it down into steps:
Step 1: Declare fields as private
Private fields cannot be accessed directly from outside the class.
Step 2: Provide public
getter and setter methods
These methods allow controlled read/write access to the fields.
Example: Encapsulating a Bank Account
public class BankAccount {
private String accountHolder;
private double balance;
// Constructor
public BankAccount(String name, double initialBalance) {
accountHolder = name;
balance = initialBalance;
}
// Getter for accountHolder
public String getAccountHolder() {
return accountHolder;
}
// Setter for accountHolder
public void setAccountHolder(String name) {
accountHolder = name;
}
// Getter for balance
public double getBalance() {
return balance;
}
// Setter for balance
public void setBalance(double amount) {
if (amount >= 0) {
balance = amount;
} else {
System.out.println("Balance cannot be negative.");
}
}
}
Using the Encapsulated Class
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount("Alice", 5000);
// Accessing data via getters
System.out.println("Account Holder: " + account.getAccountHolder());
System.out.println("Initial Balance: $" + account.getBalance());
// Modifying data via setters
account.setBalance(7000);
System.out.println("Updated Balance: $" + account.getBalance());
// Trying to set invalid balance
account.setBalance(-100);
}
}
Account Holder: Alice
Initial Balance: $5000.0
Updated Balance: $7000.0
Balance cannot be negative.
What Happens If You Skip Encapsulation?
If fields were public, any class could change the values without any checks. For instance:
account.balance = -10000; // This would be allowed if 'balance' was public
This is dangerous. You lose control over your class’s integrity. With encapsulation, such reckless modifications can be blocked.
Benefits of Encapsulation at Scale
- In large systems, encapsulation allows teams to work independently on different components without worrying about each other's internal logic.
- Helps enforce business rules via logic inside setters (e.g., disallowing negative balances).
- Improves testing and debugging by narrowing down where changes can happen.
Real-World Analogy
Think of encapsulation like using a vending machine. You interact with it through buttons (public methods) — you don’t get to reach inside and grab a drink (private fields). It controls what happens internally based on your input.
Recap
- Encapsulation = combining data + methods + access control
- Use
private
for fields - Use
public
getters and setters to expose controlled access
QUIZ
Question 1:Which of the following best describes the purpose of encapsulation in Java?
Question 2:Encapsulation can help enforce rules, such as preventing negative values in fields.
Question 3:Which steps are required to properly implement encapsulation in Java?
Question 4:What would happen if the following line of code is executed, assuming 'balance' is a public field?
account.balance = -10000;
account.balance = -10000;