Undertanding Encapsulation in Java

Undertanding Encapsulation in Java

10 Sep 2024
Beginner
45 Views
6 min read
Learn via Video Course & by Doing Hands-on Labs

Java Online Course Free with Certificate (2024)

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

Q1. Why use encapsulation?

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

Q2. What is the principle of encapsulation?

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. 

Q3. What is encapsulation in oops?

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

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
ASP.NET Core Certification TrainingSep 21SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification TrainingSep 21SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
Software Architecture and Design TrainingSep 22SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
.NET Solution Architect Certification TrainingSep 22SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
ASP.NET Core Certification TrainingSep 29SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification TrainingSep 29SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Full-Stack .NET Developer Certification TrainingOct 06SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
Angular Certification TrainingOct 06SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
.NET Solution Architect Certification TrainingOct 13SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
.NET Microservices Certification TrainingOct 13SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
ASP.NET Core ProjectOct 13SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification TrainingOct 20SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
ASP.NET Core Certification TrainingOct 20SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
Azure Developer Certification TrainingOct 27SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this