Table of contents
1.
Introduction
2.
What is Encapsulation in Java?
3.
Need for Encapsulation in Java
4.
Implementation of Java Encapsulation
4.1.
Java Encapsulation Example
4.2.
Java
4.3.
 
4.4.
Data Encapsulation Basics
4.5.
Encapsulating Data with Validation Checks
4.6.
Encapsulating Multiple Data Fields in Java
5.
Data Hiding vs. Encapsulation in Java
6.
Getter and Setter Methods
7.
Advantages of Encapsulation
7.1.
Disadvantages of Encapsulation in Java
8.
Frequently Asked Questions
8.1.
What is encapsulation in OOP?
8.2.
What are the three types of encapsulation?
8.3.
Which layer uses encapsulation?
8.4.
What are the methods of encapsulation?
9.
Conclusion
Last Updated: May 30, 2025
Easy

Encapsulation in Java

Author Saksham Gupta
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Encapsulation is a core object-oriented programming concept that involves bundling data (variables) and methods that operate on the data into a single unit or class. It restricts direct access to some of an object’s components, protecting the internal state and promoting modularity.

Encapsulation in Java means hiding an object’s internal state and requiring all interaction to be performed through an object’s methods. This protects data from unauthorized access and misuse.

In Java, encapsulation restricts direct access to class fields by making them private and exposing public getter and setter methods. This safeguards data integrity and supports flexible code maintenance.

This article covers the basics of encapsulation, why it’s important, and how to implement it effectively in Java applications.

Encapsulation in Java

What is Encapsulation in Java?

Encapsulation in Java is the process of wrapping data (variables) and methods that operate on that data into a single unit, typically a class. It means restricting direct access to some of an object’s components by making variables private and controlling access through public methods like getters and setters. This mechanism helps protect the internal state of an object and promotes data hiding, ensuring better security and modularity in programs. Encapsulation is one of the fundamental principles of object-oriented programming in Java.

Need for Encapsulation in Java

  • Encapsulation enhances data security by restricting access to class fields and methods.
  • It promotes modularity, allowing a class to be modified without affecting other parts of the program.
  • Encapsulation aids in the maintainability of code by organizing data and related methods together.
  • It allows for controlled access to class properties through getter and setter methods.
  • Encapsulation supports the concept of data hiding, protecting sensitive data from unauthorized access or modification.
  • It improves code reusability by creating self-contained classes that can be easily integrated into different programs.

Implementation of Java Encapsulation

Encapsulation in Java is implemented by making class variables private and providing public getter and setter methods to access and update these variables safely.

Java Encapsulation Example

  • Java

Java

public class Person {
// Private variables (encapsulated data)
private String name;
private int age;

// Getter for name
public String getName() {
return name;
}

// Setter for name
public void setName(String name) {
this.name = name;
}

// Getter for age
public int getAge() {
return age;
}

// Setter for age with validation
public void setAge(int age) {
if (age > 0 && age < 120) {
this.age = age;
} else {
System.out.println("Invalid age!");
}
}
}

public class Main {
public static void main(String[] args) {
Person p = new Person();

// Setting values using setters
p.setName("Rahul");
p.setAge(25);

// Getting values using getters
System.out.println("Name: " + p.getName());
System.out.println("Age: " + p.getAge());

// Trying to set invalid age
p.setAge(-5);
}
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

Name: Rahul
Age: 25
Invalid age!

Data Encapsulation Basics

In this example, name and age are declared private to hide the data from direct access outside the class. Public getter and setter methods provide controlled access, ensuring that the internal state of the object is protected.

Encapsulating Data with Validation Checks

The setAge method includes a validation check to allow only realistic age values (between 1 and 119). This prevents invalid data from corrupting the object’s state, illustrating how encapsulation helps maintain data integrity.

Encapsulating Multiple Data Fields in Java

Multiple fields like name and age can be encapsulated within the same class using the same principles: private variables and public getters/setters. This approach keeps related data bundled and secure while offering flexible access.

Data Hiding vs. Encapsulation in Java

ParametersData HidingEncapsulation
DefinitionConcealing internal data of a class from the outside world.Wrapping data (variables) and code (methods) together into a single unit.
Primary PurposeTo protect sensitive data from direct access.To achieve data hiding and to maintain control over the data.
ImplementationAchieved using access modifiers like private.Achieved by declaring fields as private and providing public getter and setter methods.
ScopeFocused solely on hiding the data of a class.Encompasses data hiding and also the bundling of data and methods together.
VisibilityControls visibility of data members outside the class.Controls both data access and the methods that can operate on the data.

Getter and Setter Methods

Getter and Setter methods in Java are used to access and modify the private fields of a class. They provide a controlled way to interact with class attributes while ensuring that encapsulation is maintained.

  1. Getter Method: A getter method retrieves the value of a private field. It typically follows the naming convention of get followed by the field name, capitalized (e.g., getName for a field name).
  2. Setter Method: A setter method updates the value of a private field. It usually follows the naming convention of set followed by the field name, capitalized (e.g., setName for a field name).

Now let's see an example of encapsulation.

Advantages of Encapsulation

  • Data Hiding: The user will be unaware of the class's internal implementation. The user will be unable to observe how the class keeps variables values. Only the user will be aware that the values are supplied to a setter method and that variables are set to that value.
  • Increased Flexibility: Depending on our needs, we can make the class's variables read-only or write-only. If we want the variables to be read-only, we must remove the setter methods like set_FunctionNmae(); if we want the variables to be write-only, we must remove the get methods like get_FunctionName().
  • Reusability: Encapsulation also promotes reusability and makes it simple to adapt to changing requirements.
  • Testing code is easy: Unit testing is simple with encapsulated code.

You can also find the output of this java compiler code here.

Disadvantages of Encapsulation in Java

  • Increased Code Complexity: Encapsulation often requires writing additional code, such as getter and setter methods, which can make the codebase more complex and lengthy.
  • Performance Overhead: The use of getter and setter methods can introduce a small performance overhead, especially in scenarios where these methods are called frequently.
  • Limited Accessibility: While encapsulation enhances security, it can also limit access to essential data or methods, which might require more effort to work around, especially in debugging or testing phases.
  • Potential Overhead in Maintenance: Managing a large number of encapsulated classes with multiple private fields and associated methods can become challenging, especially in large-scale projects where maintaining consistency becomes crucial.
  • Reduced Flexibility: Encapsulation can sometimes reduce flexibility by preventing direct access to data, which may require additional methods or modifications to work with the encapsulated data effectively.

Frequently Asked Questions

What is encapsulation in OOP?

Encapsulation is an OOP principle that bundles data and methods, restricting direct access to an object's internal state to protect and control it.

What are the three types of encapsulation?

The three types are: data encapsulation (hiding data), procedural encapsulation (hiding methods), and control encapsulation (controlling access via interfaces).

Which layer uses encapsulation?

Encapsulation is primarily used in the object layer of software design to hide internal object details and expose only necessary interfaces.

What are the methods of encapsulation?

Encapsulation is achieved using access modifiers (private, protected, public), getter and setter methods, and interfaces to control data visibility and access.

Conclusion

In this article, we have extensively discussed Encapsulation in Java. Encapsulation in Java is a powerful object-oriented programming concept that plays a crucial role in building secure, maintainable, and modular software. By bundling data and methods within a class and controlling access to the data through public methods, encapsulation enhances data security, reduces code complexity for users, and supports the principle of data hiding. 

Explore more related articles: 

Live masterclass