Encapsulation is one of the four main pillars of Object-Oriented Programming (OOP), along with inheritance, polymorphism, and abstraction.
It means binding data (variables) and methods (functions) that operate on that data into a single unit, known as a class.
In simple words, encapsulation is like keeping data safe inside a box, where the box decides who can see or modify its contents.
Understand Real-Life Example
Imagine your ATM card. You can withdraw or deposit money, but you can’t directly access the bank’s internal system.
The ATM gives you limited and controlled access, this is encapsulation in real life.
Similarly, in Java, we don’t expose the raw data of a class to the outside world. Instead, we use methods to safely read or change it.
How Encapsulation Works in Java
Encapsulation works using two simple steps:
- Make class variables private so that can’t directly form outside the class.
- Use public getter and setter methods to control how the values are read or modified.
Example: Encapsulation in Java
With this example, you can clearly shows how encapsulation works.
class BankAccount {
// Step 1: Private variables (data hiding)
private String accountHolder;
private double balance;
// Step 2: Public getters and setters
public void setAccountHolder(String name) {
if (name != null && !name.isEmpty()) {
accountHolder = name;
} else {
System.out.println("Invalid name!");
}
}
public String getAccountHolder() {
return accountHolder;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println(amount + " deposited successfully!");
} else {
System.out.println("Deposit amount must be positive.");
}
}
public double getBalance() {
return balance;
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount();
// Setting account holder using setter method
account.setAccountHolder("Riya");
// Depositing money
account.deposit(5000);
// Displaying data using getter methods
System.out.println("Account Holder: " + account.getAccountHolder());
System.out.println("Current Balance: ₹" + account.getBalance());
}
}
Output:
5000.0 deposited successfully!
Account Holder: Riya
Current Balance: ₹5000.0
- The variables accountHolder and balance are private, so they cannot be accessed directly from the Main class.
- Access is provided through public methods like getAccountHolder(), setAccountHolder(), and deposit().
Advantages of Encapsulation in Java
- One of the most powerful benefits of encapsulation is data protection.
- Encapsulation helps break large programs into smaller, self-contained modules. Each class handles its own data and behavior, which makes the overall code structure easier to understand and manage.
- Encapsulated code is easier to test and debug because data changes happen in a controlled way.
- Encapsulated classes are independent and reusable. You can use them in different parts of the same project or even in other projects without changing the internal code.
How to Implement Encapsulation in Java?
Steps to Achieve Encapsulation
- Declare variables as private.
- Use public getter methods to retrieve the values of variables.
- Use public setter methods to update the values of variables.
Example: Encapsulation in Java
Below is an example demonstrating encapsulation:
Code:
// A simple class demonstrating Encapsulation
class Car {
// Step 1: Private variables
private String brand;
private int speed;
// Step 2: Public getter for brand
public String getBrand() {
return brand;
}
// Step 3: Public setter for brand
public void setBrand(String brand) {
if (brand != null && !brand.isEmpty()) {
this.brand = brand;
} else {
System.out.println("Brand name cannot be empty!");
}
}
// Getter for speed
public int getSpeed() {
return speed;
}
// Setter for speed (with validation)
public void setSpeed(int speed) {
if (speed >= 0) {
this.speed = speed;
} else {
System.out.println("Speed cannot be negative!");
}
}
}
// Main class to test encapsulation
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
// Setting values using setter methods
myCar.setBrand("Tesla");
myCar.setSpeed(120);
// Getting values using getter methods
System.out.println("Car Brand: " + myCar.getBrand());
System.out.println("Car Speed: " + myCar.getSpeed() + " km/h");
}
}
Output:
Car Brand: Tesla
Car Speed: 120 km/h
Explanation:
- brand and speed are private, so they can’t be accessed directly.
- We can only set or get their values through public methods.
- Data integrity is maintained by validation checks inside the setter methods.
Exercise: Smart Thermostat System (Encapsulation Practice)
Implement Encapsulation to create a Thermostat class that manages a smart home’s temperature in a safe and controlled way.
You need to create a program that controls the temperature of a room.
The class should:
- Keep the temperature private (cannot be accessed directly).
- Allow only valid temperature values to be set (between 16°C and 30°C).
- Provide a status message when the temperature is changed.
- Allow users to read the current temperature using a getter method.
Code Example (Write by Yourself)
// Create a class named Thermostat
class Thermostat {
// Step 1: Declare a private variable to store temperature
private int temperature;
// Step 2: Create a setter method to set temperature with validation
public void setTemperature(int newTemp) {
if (newTemp >= 16 && newTemp <= 30) {
temperature = newTemp;
System.out.println("Temperature set to " + temperature + "°C");
} else {
System.out.println("Invalid temperature! Please set between 16°C and 30°C.");
}
}
// Step 3: Create a getter method to get the current temperature
public int getTemperature() {
return temperature;
}
}
// Step 4: Create a Main class to test encapsulation
public class Main {
public static void main(String[] args) {
Thermostat room = new Thermostat();
// Trying to set valid and invalid temperatures
room.setTemperature(25); // valid
room.setTemperature(10); // invalid
// Getting the current temperature
System.out.println("Current room temperature: " + room.getTemperature() + "°C");
}
}
Expected Output (Example Run):
Temperature set to 25°C
Invalid temperature! Please set between 16°C and 30°C.
Current room temperature: 25°C
Also Learn Important Topics of Java
- What are the operators in Java Programming?
- What are Data Types in Java?
- What are the Variables in Java?
- Learn Java syntax.
- What is Java if else statements?
- What is method overloading in Java?
- What are the Classes and Objects in Java?

M.Sc. (Information Technology). I explain AI, AGI, Programming and future technologies in simple language. Founder of BoxOfLearn.com.