Author Topic: What is encapsulation in java?  (Read 4155 times)

Musfiqur Rahman

  • Newbie
  • *
  • Posts: 45
    • View Profile
    • Musfiqur Rahman
What is encapsulation in java?
« on: March 23, 2023, 01:33:48 PM »
Encapsulation is one of the four fundamental principles of Object-Oriented Programming (OOP) in Java. It refers to the practice of bundling data and methods that operate on that data within a single unit or class, and restricting direct access to the data from outside the class.

In encapsulation, the data is hidden or protected from the outside world and can only be accessed through the methods defined in the class. This ensures that the data is accessed and modified in a controlled and consistent manner, reducing the possibility of errors and improving the overall maintainability of the code.

Here's an example of encapsulation in Java:

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if(age > 0) {
            this.age = age;
        }
    }
}


In this example, the Person class has two private fields, name and age, and public getter and setter methods to access and modify these fields. The private keyword ensures that these fields can only be accessed from within the Person class, and not directly from outside the class.

The getName() and getAge() methods provide read-only access to the name and age fields, respectively, while the setName() and setAge() methods provide write access to these fields. The setAge() method also includes a check to ensure that the age is a positive integer before modifying the age field.

By encapsulating the data within the Person class and providing controlled access through methods, we can ensure that the data is accessed and modified in a consistent and controlled manner. This improves the maintainability of the code and reduces the possibility of errors caused by direct access to the data from outside the class.