Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Java

Encapsulation in Java: A Comprehensive Guide with Practical Example

What is Encapsulation in Java?

Encapsulation is one of the core pillars of object‑oriented design in Java. It bundles data (fields) and the operations that manipulate that data (methods) into a single, self‑contained unit—the class. By hiding the internal state behind a well‑defined interface, encapsulation protects objects from unintended interference and makes code easier to maintain and test.

In this tutorial you will learn:

Click here if the video is not accessible

Learn Encapsulation with an Example

To illustrate encapsulation, consider a simple bank‑account class that offers deposit and balance‑display functionality.

class Account {
    private int accountNumber;
    private int accountBalance;

    public void showData() {
        // code to display data
    }

    public void deposit(int amount) {
        if (amount < 0) {
            // show error
        } else {
            accountBalance = accountBalance + amount;
        }
    }
}

Imagine a malicious actor has access to the source code and attempts to inject a negative deposit of -100. There are two common attack vectors:

Approach 1: Directly modifying the accountBalance field. Because the field is declared private, it is inaccessible from outside the Account class, preventing this attack.

Encapsulation in Java: A Comprehensive Guide with Practical Example

As you can see, the private modifier enforces encapsulation and shields the internal state.

Encapsulation in Java: A Comprehensive Guide with Practical Example

Therefore the hacker cannot tamper with the balance directly.

Encapsulation in Java: A Comprehensive Guide with Practical Example

Approach 2: Using the public deposit method to add a negative amount. The method contains a validation check that rejects any amount less than zero, thwarting this attempt as well.

Encapsulation in Java: A Comprehensive Guide with Practical Example

Thus, encapsulation ensures that only legitimate operations can modify the object’s state.

Encapsulation in Java: A Comprehensive Guide with Practical Example

The entire class behaves like a sealed capsule—data is hidden, and interaction occurs solely through well‑defined messages. This is the essence of encapsulation.

Encapsulation in Java: A Comprehensive Guide with Practical Example

Data Hiding in Java

Data hiding is the practice of restricting direct access to an object's fields from outside its defining class. In Java, the private keyword enforces this restriction, making the field invisible to all other classes. This keeps the internal representation opaque, allowing developers to modify it without breaking dependent code.

Sometimes a less restrictive access level, such as protected or public, is required for inheritance or utility classes. However, encapsulation encourages using private fields coupled with controlled accessor methods.

Getter and Setter Methods in Java

Getters (accessors) and setters (mutators) provide a controlled interface for reading and updating private fields. They enable validation, logging, or lazy initialization while preserving encapsulation.

Example:

class Account {
    private int accountNumber;
    private int accountBalance;

    // accessor
    public int getBalance() {
        return this.accountBalance;
    }

    // mutator
    public void setNumber(int num) {
        this.accountNumber = num;
    }
}

Here, getBalance() returns the current balance, while setNumber() assigns a new account number.

Abstraction vs. Encapsulation

Although related, abstraction and encapsulation serve distinct purposes:

Think of a smartphone: the complex circuitry is encapsulated behind a touch interface, while abstraction provides the high‑level functions such as dialing or texting.

Advantages of Encapsulation in Java

Java

  1. Mastering Java Encapsulation: A Practical Guide to Data Hiding
  2. Java Variables and Data Types – A Comprehensive Guide with Examples
  3. Understanding Java Classes and Objects: Clear Concepts, Practical Examples
  4. Understanding Java String.charAt(): Syntax, Return Type, Exceptions, and a Practical Example
  5. Mastering Java’s String.endsWith(): How to Check String Suffixes with Examples
  6. Java HashMap: A Comprehensive Guide
  7. Command‑Line Arguments in Java: A Practical Guide with Code Examples
  8. Java Inheritance Explained: Types, Syntax, and Practical Examples
  9. Polymorphism in Java: A Comprehensive Guide with Practical Examples
  10. Understanding Java's throws Keyword: Examples & Best Practices