Encapsulation is one of the four fundamental principles of object-oriented programming (OOP) in Java. It is the process of binding data and corresponding methods (behavior) together into a single unit called a class.
In other words, encapsulation is a programming technique that bundles data and methods that operate on that data into a class and controls access to them using access modifiers. This helps protect the object’s internal state (data) from unintended modification, outside interference, and misuse.
A Java class provides the structure for encapsulation by bundling data and methods together. This is a perfect example of encapsulation in Java. However, a class is considered properly encapsulated only when it restricts direct access to its data using appropriate access modifiers.
A medicine capsule is a real-life example of encapsulation because it combines different medicines into a single unit while hiding their internal composition.
Similarly, a class in Java bundles data (fields) and methods that operate on that data into a single unit. If the medicines represent the data (fields) and the capsule represents the class, then the process of combining them into a single unit while hiding the internal details is called encapsulation, as shown in the figure below.
Let’s understand encapsulation in Java better by taking real-time examples.
Real-Time Examples of Encapsulation in Java
Real-Time Example 1: Email Account Login
When you log in to your email accounts such as Gmail or Yahoo Mail, there are a lot of internal processes taking place in the backend, and you have no control over them.
When you enter your username and password, the password is securely verified before access to your account is granted. The internal implementation is hidden from you, and you interact only through the login interface.
This is an example of encapsulation because the internal implementation is hidden, and access is provided only through a controlled interface. You do not have control over how the password has been verified. Thus, it keeps your account safe from being misused.
Real-Time Example 2: Bank Account
Suppose you have a bank account. If the balance field in the bank’s software were declared as public, anyone could access or modify your account balance directly. This would be a serious security risk. To prevent this, the balance field is declared private so that anyone cannot see your account balance.
If an account holder wants to check their balance or perform transactions, they must use public methods such as getBalance(), deposit(), or withdraw() defined inside that class. These methods may first verify the user’s identity by checking authentication details such as a username, account number, password, or other credentials before allowing access.
This approach protects the internal data of the account from unauthorized access and modification. Restricting direct access to data and providing controlled access through methods is an example of encapsulation in Java.
How to Achieve Encapsulation in Java
There are two important steps whereby we can achieve or implement encapsulation in Java:
- Declare the instance variables (fields) of a class as private so that they cannot be accessed directly by anyone from outside the class.
- Provide public methods, such as getter and setter methods, in the class to read (retrieve) or modify (set) the values of the private fields when required.
Java Encapsulation Example Programs
Let’s understand encapsulation in Java with the help of the following example programs.
Example 1:
class Student
{
private String name;
public String getName()
{
return name;
}
public void setName(String studentName)
{
name = studentName;
}
}
public class EncapsulationTest {
public static void main(String[] args)
{
// Create an object of Student class.
Student obj = new Student();
// Set the value of private field.
obj.setName("Amit");
// Read the value of private field.
String studentName = obj.getName();
System.out.println(studentName);
}
}Output:
Amit
In this example:
- The Student class contains a private field name, which cannot be accessed directly from outside the class.
- The getName() method is a public getter method that returns the value of the private field name.
- The setName() method is a public setter method that assigns a value to the private field name.
- In the main() method, we have created an object of the Student class using the new keyword.
- Then, we have called the setName() method to assign the value “Amit” to the private field name.
- After that, we have called the getName() method to retrieve the value of the private field name.
- Since the name field is private, you can only access it through the public getter and setter methods. This ensures controlled access to the object’s internal data and demonstrates the concept of encapsulation in Java.
Example 2:
Let’s take another example program in which we will declare all three data fields as private, which cannot be accessed directly from outside the class. We will access these methods via public methods only from outside the class.
Fields stdName, stdRoll, and stdId will be made a hidden data field using the encapsulation technique of OOPs concepts in Java. Look at the example code to understand better.
class Student
{
// Declare variables as private in the class.
private String stdName;
private int stdRollNo;
private int stdId;
// Declare the public getter method for each private variable.
public String getStdName() {
return stdName;
}
public int getStdRollNo() {
return stdRollNo;
}
public int getStdId() {
return stdId;
}
// Declare the public setter method for each private variable.
public void setStdName(String name) {
stdName = name;
}
public void setStdRollNo(int rollNo) {
stdRollNo = rollNo;
}
public void setStdId(int id) {
stdId = id;
}
}
public class EncapsulationTest {
public static void main(String[] args)
{
// Create an object of the class Student by using the new keyword.
Student obj = new Student();
// Call setter methods to set the values of private fields.
obj.setStdName("Kiran");
obj.setStdRollNo(4);
obj.setStdId(12345);
// Call the getter methods to read the value of private fields.
System.out.println("Student's Name: " +obj.getStdName());
System.out.println("Student's Roll no.: " +obj.getStdRollNo());
System.out.println("Student's ID: " +obj.getStdId());
}
}Output:
Student Name: Kiran Student Roll no.: 4 Student ID: 12345
Encapsulation with Java Records
In traditional Java programming, encapsulation is achieved by declaring instance variables as private and providing controlled access through public getter and setter methods. This approach allows you to protect an object’s internal state and allows validation before state changes occur.
Standardized in Java 16 (after previewing in Java 14 and 15), Java introduced Java Records, a special type of class designed to represent immutable data with minimal boilerplate.
When you declare a record, the Java compiler automatically generates private final fields, a canonical constructor, component-named accessor methods (e.g., name() instead of getName()), and custom implementations of equals(), hashCode(), and toString().
Although records eliminate the need to write custom accessor methods and constructors, they do not replace encapsulation—they redefine it for immutable data. Furthermore, you can enforce strict state validation at instantiation using compact constructors.
Since record components are private final and cannot be reassigned after construction, records provide built-in shallow immutability. This makes them exceptionally well-suited for Data Transfer Objects (DTOs), configuration objects, value objects, and other transparent data models.
To learn more about record syntax, features, advantages, limitations, and practical examples, read our detailed tutorial.
Validation Using Encapsulation in Java
One of the biggest advantages of encapsulation in Java is data validation. Encapsulation not only hides an object’s data but also allows you to validate input before updating the object’s state. This helps ensure that objects always contain valid and consistent data while preventing accidental or invalid modifications from outside the class.
Since the fields are declared as private, they cannot be accessed or modified directly from outside the class. Instead, users must access or modify the data through public setter and getter methods.
The setter methods provide a central place to validate input before storing it in the object’s fields. If the input is valid, the value is stored; otherwise, the setter method can reject the value, display an error message, or throw an exception. Let’s take examples based on it.
Example 3: Validation Using Encapsulation
Suppose a school student’s age should always be between 5 and 18.
class Student {
private int age;
// Setter with validation
public void setAge(int age) {
if (age >= 5 && age <= 18) {
this.age = age;
} else {
System.out.println("Invalid age! Age must be between 5 and 18.");
}
}
public int getAge() {
return age;
}
}
public class EncapsulationTest {
public static void main(String[] args) {
Student st = new Student();
st.setAge(15); // Valid age
System.out.println("Student Age: " + st.getAge());
st.setAge(-10); // Invalid age
System.out.println("Student Age: " + st.getAge());
}
}Output:
Student Age: 15 Invalid age! Age must be between 5 and 18. Student Age: 15
How Does Validation Work?
- The age field is declared as private, so you cannot access it directly from outside the class.
- The setAge() method checks whether the entered age is valid.
- If the age is between 5 and 18, it stores the value.
- If the age is invalid, it displays an error message and does not change the stored value.
- The getAge() method returns the current valid age.
What Happens Without Encapsulation?
If the field is public, anyone can assign an invalid value.
class Student {
public int age;
}
public class EncapsulationTest {
public static void main(String[] args) {
Student st = new Student();
st.age = -10; // Invalid value
System.out.println("Student Age: " + st.age);
}
}Output:
Student Age: -10
The object now contains invalid data because there is no validation.
Looking for more advanced example programs?
If you want to explore more complex real-world use cases, see our complete guide on Encapsulation Programs in Java with Best Practices, where we cover read-only classes, constructor-driven encapsulation, and enterprise design patterns.
Tightly Encapsulated Class in Java
If all instance variables (fields) of a class are declared as private, the class is called a tightly encapsulated class in Java.
To determine whether a class is tightly encapsulated, you only need to check whether all of its fields are private. It does not matter whether the class contains getter or setter methods or whether those methods are public, protected, or private. Let’s understand the concept of tightly encapsulated class with the following examples.
Example 4:
public class Account {
private double balance;
public double getbalance() {
return balance;
}
}The Account class is tightly encapsulated because its only field (balance) is declared as private.
Example 5:
class A {
private int x = 20;
}
class B extends A {
int y = 50;
}
class C extends A {
private int z = 10;
}In this example:
- Class A is tightly encapsulated because all its fields are private.
- Class B is not tightly encapsulated because y is not private.
- Class C is tightly encapsulated because its own field z is private, and class A is also tightly encapsulated.
Example 6:
class P {
int x = 10;
}
class Q extends P {
private int y = 20;
}
class R extends Q {
private int z = 30;
}In this example:
- Class P is not tightly encapsulated because field x is not private.
- Class Q is not tightly encapsulated because it inherits the non-private field a from class P.
- Class R is not tightly encapsulated because the non-private field x is still inherited from class P.
Therefore, none of these classes is tightly encapsulated.
Key Points About Tightly Encapsulated Classes
- Every field declared in the class must be private.
- Getter and setter methods are not required for a class to be tightly encapsulated.
- The access modifiers of getter and setter methods do not affect whether a class is tightly encapsulated.
- If a parent class is not tightly encapsulated, then none of its child classes can be tightly encapsulated because they inherit the parent class’s non-private fields by default.
- Non-private fields defined in a parent class prevent all of its subclasses from being tightly encapsulated.
Advantage of Encapsulation in Java
There are the following advantages of encapsulation in Java. They are as follows:
- The encapsulated code is more flexible and easy to change with new requirements.
- It prevents the other classes from accessing the private fields.
- Encapsulation allows modifying the implemented code without breaking other code that has implemented the code.
- It keeps the data and codes safe from external inheritance. Thus, encapsulation helps to achieve security.
- It improves the maintainability of the application.
- If you don’t define the setter method in the class, then the fields can be made read-only.
- If you don’t define the getter method in the class, then the fields can be made write-only.
- If you define both getter and setter methods in the class, then the fields can be made read-write.
Disadvantage of Encapsulation in Java
The major disadvantage of encapsulation in Java is it increases the length of the code and slows shutdown execution.
Data Hiding in Java
Data hiding in Java is an important concept of object-oriented programming (OOP). It restricts direct access to an object’s data members (fields) from outside the class, thereby protecting the data from unauthorized access and modification. This feature is known as data hiding. With data hiding, we can achieve data security.
The main purpose of data hiding is to protect an object’s internal state (data). It does not allow direct access to or modification of the object’s private data. It provides access through public methods, which can perform validation, authentication, or other checks before allowing the data to be read or modified.
For example, you cannot directly access the data stored in your Gmail account. You must first provide a valid username and password. Only after successful authentication are you allowed to access your Gmail inbox. Similarly, in Java, you can access the private data only through the class’s public methods.
How to Achieve Data Hiding Programmatically?
You can achieve data hiding by declaring data members (fields) as private. If the fields are declared as private in the class, nobody can access them from outside the class. They are accessed or modified through public methods, such as getter and setter methods.
The biggest advantage of data hiding is that it improves security, data integrity, and maintainability by preventing unauthorized or accidental modification of an object’s data.
Key Points of Encapsulation in Java
- Encapsulation is one of the four fundamental principles of object-oriented programming (OOP) in Java.
- The other three OOP principles are abstraction, inheritance, and polymorphism.
- Encapsulation is commonly explained as the combination of data hiding and abstraction.
- Encapsulation = Data Hiding + Abstraction
- Data hiding protects an object’s internal data from direct access.
- Controlled access to private data is usually provided through public methods, such as getter and setter methods.
- Data hiding helps improve security, data integrity, and code maintainability.
- Encapsulation allows you to control how an object’s data is accessed and modified.
- Encapsulation makes Java programs more secure, maintainable, reusable, and flexible.
Test Your Knowledge: Quick Encapsulation Quiz
Question: If class Parent has a non-private variable int x = 10;, and class Child extends Parent has only private int y = 20;, is class Child tightly encapsulated?
A) Yes
B) No
C) It depends on getter/setter methods
D) Only if y is final
Correct Answer: B) No
Explanation:
A class cannot be tightly encapsulated if its parent class contains non-private fields, because the child class inherits those non-private variables.
Want to practice more?
👉 Take the Full 25-Question Java Encapsulation Quiz (with instant scores and detailed solutions).




