Year End Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
Undertanding Encapsulation in Java

Undertanding Encapsulation in Java

10 Sep 2024
Beginner
548 Views
6 min read
Learn with an interactive course and practical hands-on labs

Free Java Course With Certificate

Java Encapsulation

Encapsulation is a fundamental concept in object-oriented programming (OOP) and is critical for developing clean, efficient, and maintainable Java code. It refers to the combination of data (variables) and methods (functions) for manipulating data into a single entity known as a class. This approach blocks direct access to parts of the object's components, improving security, simplifying the software, and making it easier to maintain.

In this Java Tutorial, We will explore all about Encapsulation in Java including What is Java Encapsulation, How Encapsulation Works in Java, Benefits of Encapsulation in Java,etc.

What is Encapsulation in Java

Encapsulation in Java is achieved by making class fields (data members) private but offering public getter and setter methods for accessing and updating these fields. This restriction over data access ensures that data is only modified via well-defined interfaces, protecting the object's internal state.

What is Encapsulation in Java

Key Points of Encapsulation:

  • Data Hiding: It limits the visibility of internal object states and only enables access to public methods.
  • Controlled Access: The usage of getter and setter methods allows for controlled access to variables.
  • Flexibility: The internal representation of the data can change without affecting the external code that relies on it.

How Encapsulation Works in Java?

Let us break down encapsulation with an example. Assume we have a student class. Without encapsulation, the internal fields would be visible to anyone, perhaps leading to misuse or unwanted changes.

Example Without Encapsulation:

class Student
{
    String name;
    int age;
}
In this code, both the name and age attributes are publicly accessible and can be changed directly, even in unacceptable ways.

Example with Encapsulation:

class Employee{
    private String name;
    private int age;
    // Getter method for name
    public String getName() {
        return name;
    }
    // Setter method for name
    public void setName(String name) {
        this.name = name;
    }
    // Getter method for age
    public int getAge() {
        return age;
    }
    // Setter method for age
    public void setAge(int age) {
        if(age > 0) {
            this.age = age;
        } else {
            System.out.println("Age cannot be negative");
        }
    }
}

Explanation

The field's name and age are private, which means they cannot be accessed directly from outside the class. Instead, values are retrieved and modified using the public getter and setter methods. The age setter additionally incorporates validation logic to avoid assigning erroneous values, such as negative ages.

Benefits of Encapsulation

  • Encapsulation provides data security by hiding internal details and regulating access to fields, preventing misuse or corruption. Improved maintainability: Because the internal implementation details are concealed, changes to the class internals (such as data structures) have no impact on the remainder of the codebase that uses the class.
  • Flexibility in Modification: Encapsulation enables developers to update a portion of the code without changing the complete program. For example, a change in how data is stored internally can be introduced without affecting the code that interacts with the object, as long as the public methods remain unchanged.
  • Reusability: Encapsulated code is simpler to reuse since it separates functionality within a class. You can use objects without having to understand how they work internally, which reduces programming complexity.
  • Reduced Complexity: Encapsulation helps to break down the system into smaller, more manageable chunks (classes) and improves code readability by grouping relevant variables and methods together.

Real-World Example of Encapsulation in Java

Now, Let's Consider a bank account application. Sensitive information, such as account balances, should not be accessed or modified without sufficient validation.
class BankAccount {
    private double balance;

    // Getter for balance
    public double getBalance() {
        return balance;
    }

    // Deposit method with validation
    public void deposit(double amount) {
        if(amount > 0) {
            balance += amount;
        } else {
            System.out.println("Deposit amount must be positive");
        }
    }

    // Withdraw method with validation
    public void withdraw(double amount) {
        if(amount > 0 && amount <= balance) {
            balance -= amount;
        } else {
            System.out.println("Invalid withdrawal amount");
        }
    }
}

Explanation

In this example, the BankAccount class encapsulates the balance field, and access to it is controlled by the deposit() and withdraw() methods. The validation logic within these methods ensures that the account balance is not changed in an inappropriate manner. 
Conclusion
Encapsulation is one of Java's four essential OOP principles, along with inheritance, polymorphism, and abstraction. Controlling access to the class's internal state promotes cleaner, more maintainable code and prevents data from being misused. Proper encapsulation ensures that software remains adaptable and robust as the system evolves over time. Also, consider our Full Stack Java Course to become a master in Full Stack Java Development.

FAQs

Encapsulation can used when dealing with secure data or methods because it can restrict which functions or users have access to certain information.

Encapsulation is one of the fundamentals of OOP (object-oriented programming). It refers to the bundling of data with the methods that operate on that data. 

In object-oriented programming (OOP), encapsulation is the practice of bundling related data into a structured unit, along with the methods used to work with that data
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at ScholarHat)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this