# Encapsulation

Encapsulation is one of the four fundamental concepts of object-oriented programming (OOP). It refers to the bundling of data and methods that operate on that data within a single unit, known as a class. This concept helps to protect the data and methods from outside interference, as it restricts direct access to them.

In Java, encapsulation is achieved by declaring the data members of a class as private and providing public methods to access and modify those data members. For example:

```java
class Person {
  private String name;
  private int age;

  public String getName() {
    return name;
  }

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

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }
}
```

In this example, the `name` and `age` variables are declared as private, which means that they cannot be accessed directly from outside the class. The `getName()` and `setName()` methods provide public access to the `name` variable, and the `getAge()` and `setAge()` methods provide public access to the `age` variable.

Encapsulation has several benefits, including:

* It protects data from accidental or malicious modification.
* It makes code more modular and reusable.
* It promotes good design practices.

Encapsulation is a powerful tool that can be used to improve the quality and maintainability of our code.

Here are some additional things to keep in mind about encapsulation in Java:

* The private members of a class can only be accessed by the methods of that class.
* The public methods of a class can be accessed by any code that has a reference to an object of that class.
* Encapsulation can be used to hide implementation details from users of a class.
* Encapsulation can be used to enforce good design practices, such as single responsibility and loose coupling.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://codewithmeiy.gitbook.io/core-java/object-oriented-programming-oops/encapsulation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
