---
description: Encapsulation is a mechanism of wrapping data (variables) and code together as a single unit. This Java tutorial explains encapsulation and data hiding with examples.
title: Encapsulation in Java
image: https://www.guru99.com/images/encapsulation-in-java.png
---

 

[Skip to content](#main) 

**⚡ Smart Summary**

Encapsulation in Java is a mechanism that wraps variables and methods together as a single unit while hiding internal details. It protects an object’s data using private fields and controlled access through public getter and setter methods.

* 🔒 **Encapsulation Defined:** Wraps data and methods into one unit while hiding internal implementation details.
* 🛡️ **Data Hiding:** Declaring variables private blocks outside classes from accessing them directly.
* 🔑 **Getter and Setter:** Public accessor and mutator methods read and update private values safely.
* 🧩 **Abstraction vs Encapsulation:** Encapsulation handles “how”, abstraction handles “what” a class does.
* ✅ **Advantages:** Improves security, testability, and lets developers change code with minimal side effects.

[ Read More ](javascript:void%280%29;) 

![Encapsulation in Java](https://www.guru99.com/images/encapsulation-in-java.png)

## What is Encapsulation in Java?

**Encapsulation in Java** is a mechanism to wrap up variables(data) and methods(code) together as a single unit. It is the process of hiding information details and protecting data and behavior of the object. It is one of the four important OOP concepts. The encapsulate class is easy to test, so it is also better for unit testing.

Click [here](https://www.guru99.com/faq#faq1) if the video is not accessible   

## Learn Encapsulation in Java with Example

To understand what is encapsulation in detail consider the following bank account class with deposit and show balance methods

class Account {
    private int account_number;
    private int account_balance;

    public void show Data() {
        // code to show data
    }

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

Suppose a hacker managed to gain access to the code of your bank account. Now, he tries to deposit amount -100 into your account by two ways. Let see his first method or approach.

**Approach 1:** He tries to deposit an invalid amount (say -100) into your bank account by manipulating the code.

[](https://www.guru99.com/images/java/052016%5F0638%5FLearnJavaEn1.jpg)

Now, the question is – _Is that possible?_ Let investigate. Usually, a variable in a class are set as “private” as shown below. It can only be accessed with the methods defined in the class. No other class or object can access them.

[](https://www.guru99.com/images/java/052016%5F0638%5FLearnJavaEn2.jpg)

If a data member is private, it means it can only be accessed within the same class. No outside class can access private data member or variable of other class. So in our case hacker cannot deposit amount -100 to your account.

[](https://www.guru99.com/images/java/052016%5F0638%5FLearnJavaEn3.jpg)

**Approach 2:** Hacker’s first approach failed to deposit the amount. Next, he tries to do deposit a amount -100 by using “deposit” method.

[](https://www.guru99.com/images/java/052016%5F0638%5FLearnJavaEn4.jpg)

But method implementation has a check for negative values. So the second approach also fails.

[](https://www.guru99.com/images/java/052016%5F0638%5FLearnJavaEn5.jpg)

Thus, you never expose your data to an external party. Which makes your application secure.

[](https://www.guru99.com/images/java/052016%5F0638%5FLearnJavaEn6.jpg)

The entire code can be thought of a capsule, and you can only communicate through the messages. Hence the name encapsulation.

## Data Hiding in Java

**Data Hiding in Java** is hiding the variables of a class from other classes. It can only be accessed through the method of their current class. It hides the implementation details from the users. But more than data hiding, it is meant for better management or grouping of related data. To achieve a lesser degree of encapsulation in Java, you can use modifiers like “protected” or “public”. With encapsulation, developers can change one part of the code easily without affecting other.

## Getter and Setter in Java

**Getter and Setter in Java** are two conventional methods used to retrieve and update values of a variable. They are mainly used to create, modify, delete and view the variable values. The setter method is used for updating values and the getter method is used for reading or retrieving the values. They are also known as an accessor and mutator.

The following code is an example of getter and setter methods:

class Account{
private int account_number;
private int account_balance;
    // getter method
    public int getBalance() {
        return this.account_balance;
    }
    // setter method
    public void setNumber(int num) {
        this.account_number = num;
    }
}

In above example, getBalance() method is getter method that reads value of variable account\_balance and setNumber() method is setter method that sets or update value for variable account\_number.

## Abstraction vs. Encapsulation

Often encapsulation is misunderstood with [Abstraction](https://www.guru99.com/java-data-abstraction.html). Lets study-

* Encapsulation is more about “How” to achieve a functionality
* Abstraction is more about “What” a class can do.

A simple example to understand this difference is a mobile phone. Where the complex logic in the circuit board is encapsulated in a touch screen, and the interface is provided to abstract it out.

### RELATED ARTICLES

* [What is JVM? Explain JVM Architecture ](https://www.guru99.com/java-virtual-machine-jvm.html "What is JVM? Explain JVM Architecture")
* [How to Generate Random Number in Java ](https://www.guru99.com/generate-random-number-java.html "How to Generate Random Number in Java")
* [Groovy Script Tutorial for Beginners ](https://www.guru99.com/groovy-tutorial.html "Groovy Script Tutorial for Beginners")
* [Top 50 JDBC Interview Questions and Answers (2026) ](https://www.guru99.com/jdbc-interview-questions.html "Top 50 JDBC Interview Questions and Answers (2026)")

## Advantages of Encapsulation in Java

* Encapsulation is binding the data with its related functionalities. Here functionalities mean “methods” and data means “variables”
* So we keep variable and methods in one place. That place is “class.” Class is the base for encapsulation.
* With Java Encapsulation, you can hide (restrict access) to critical data members in your code, which improves security
* As we discussed earlier, if a data member is declared “private”, then it can only be accessed within the same class. No outside class can access data member (variable) of other class.
* However, if you need to access these variables, you have to use **public “getter” and “setter”** methods.

## FAQs

🔀 What is the difference between encapsulation and abstraction in Java?

Encapsulation focuses on how functionality is achieved by binding data and methods and hiding internal details. Abstraction focuses on what a class does by exposing only essential features and hiding complexity behind a simple interface.

🔐 How do you achieve encapsulation in Java?

Declare class variables as private, then provide public getter and setter methods to read and update them. This restricts direct access and lets the class control how its data is used.

🔑 What are getter and setter methods used for?

Getter methods read or retrieve the value of a private variable, while setter methods update it. They allow controlled access and let you add validation logic before changing a value.

🤖 How can AI help apply encapsulation in Java code?

AI can generate private fields with matching getters and setters, suggest validation inside setters, and refactor public fields into encapsulated members, helping developers follow OOP best practices quickly and consistently.

🧠 Can AI detect encapsulation violations in code?

Yes. AI-assisted static analysis can flag public mutable fields, direct access to internal state, and missing validation, then recommend encapsulating the data with private access and accessor methods to improve security.

#### Summarize this post with:

ChatGPT Perplexity Grok Google AI 

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.** 

##### Sign up for the newsletter

Subscribe for Free 

You have successfully subscribed.  
Please check your inbox. 

![AI-Newsletter]() Chosen by over **350,000+** professionals 

[Scroll to top ](#wrapper)Scroll to top 

× 

Toggle Menu Close 

Search for: 

Search

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/encapsulation-in-java.png","url":"https://www.guru99.com/images/encapsulation-in-java.png","width":"700","height":"250","caption":"Encapsulation in Java","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/encapsulation-in-java.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/java-tutorials","name":"Java Tutorials"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/encapsulation-in-java.html","name":"Encapsulation in Java"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/encapsulation-in-java.html#webpage","url":"https://www.guru99.com/encapsulation-in-java.html","name":"Encapsulation in Java","dateModified":"2026-06-30T17:22:55+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/encapsulation-in-java.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/encapsulation-in-java.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/james","name":"James Hartman","description":"I am James Hartman, a seasoned professional in Oracle Certified Java Professional tutorials, specializing in crafting comprehensive guides to help you excel in your Java certification journey.","url":"https://www.guru99.com/author/james","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/james-hartman-author-v2-120x120.png","url":"https://www.guru99.com/images/james-hartman-author-v2-120x120.png","caption":"James Hartman","inLanguage":"en-US"},"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"Java Tutorials","headline":"Encapsulation in Java","description":"Encapsulation is a mechanism of wrapping data (variables) and code together as a single unit. This Java tutorial explains encapsulation and data hiding with examples.","keywords":"java","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/james","name":"James Hartman"},"dateModified":"2026-06-30T17:22:55+05:30","image":{"@id":"https://www.guru99.com/images/encapsulation-in-java.png"},"copyrightYear":"2026","name":"Encapsulation in Java","subjectOf":[{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"What is the difference between encapsulation and abstraction in Java?","acceptedAnswer":{"@type":"Answer","text":"Encapsulation focuses on how functionality is achieved by binding data and methods and hiding internal details. Abstraction focuses on what a class does by exposing only essential features and hiding complexity behind a simple interface."}},{"@type":"Question","name":"How do you achieve encapsulation in Java?","acceptedAnswer":{"@type":"Answer","text":"Declare class variables as private, then provide public getter and setter methods to read and update them. This restricts direct access and lets the class control how its data is used."}},{"@type":"Question","name":"What are getter and setter methods used for?","acceptedAnswer":{"@type":"Answer","text":"Getter methods read or retrieve the value of a private variable, while setter methods update it. They allow controlled access and let you add validation logic before changing a value."}},{"@type":"Question","name":"How can AI help apply encapsulation in Java code?","acceptedAnswer":{"@type":"Answer","text":"AI can generate private fields with matching getters and setters, suggest validation inside setters, and refactor public fields into encapsulated members, helping developers follow OOP best practices quickly and consistently."}},{"@type":"Question","name":"Can AI detect encapsulation violations in code?","acceptedAnswer":{"@type":"Answer","text":"Yes. AI-assisted static analysis can flag public mutable fields, direct access to internal state, and missing validation, then recommend encapsulating the data with private access and accessor methods to improve security."}}]}],"@id":"https://www.guru99.com/encapsulation-in-java.html#schema-26178","isPartOf":{"@id":"https://www.guru99.com/encapsulation-in-java.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/encapsulation-in-java.html#webpage"}}]}
```
