July 16 2026
Encapsulation is one of the four fundamental pillars of object-oriented programming (OOP) alongside abstraction, inheritance, and polymorphism.
What is Encapsulation in Java?
Encapsulation in Java refers to the process of wrapping data (variables) and the methods that act on that data into a single unit called a class.
By declaring class variables as private and accessing them via public getter and setter methods,
Java ensures that object fields are hidden from other classes and only modifiable through well-defined interfaces.
How to Achieve Encapsulation in Java
Here are the simple steps to implement it:
Declare class variables as private.
Provide public getter and setter methods to access and update the value of the private variables.
Syntax
public class GRT
{
//pojo
private int price = 13190;
public int getPrice(){
return this.price;
}
public void setPrice(int price){
if (price >= 125000){
this.price = price;
}
}
}
public class Customer
{
public static void main(String[] args)
{
GRT grt = new GRT();
System.out.println(grt.getPrice());
grt.setPrice (10000);
System.out.println(grt.getPrice());
}
}
Why Use Encapsulation?
Encapsulation is used for the following reasons:
Data Hiding: Internal object details are hidden from the outside world.
Control Access: You define exactly how important variables can be accessed or modified.
Increased Flexibility: You can change the internal implementation without affecting external code.
Improved Maintainability: Cleaner, more modular code is easier to debug and update.
Security: Sensitive data can only be accessed through well-defined methods.
These points are typically cited as key advantages of encapsulation in Java, especially in large-scale enterprise applications.
Top comments (0)