Encapsulation in Java is a fundamental concept in object-oriented programming (OOP) that refers to the bundling of data and methods that operate on that data within a single unit, which is called a class in Java. It is a way of hiding the implementation details of a class from outside access and only exposing a public interface that can be used to interact with the class. Encapsulation is achieved in Java by declaring the variables of a class as private and providing public setter and getter methods to modify and view the variable values.
Here are some benefits of encapsulation in Java:
- Increases modularity and maintainability by making it easier to change the implementation without affecting other parts of the code.
- Enables data abstraction, allowing objects to be treated as a single unit.
- Allows for easy addition of new methods and fields without affecting the existing code.
- Provides control over the data members and data methods of a class.
- Helps to achieve data hiding, which prevents other classes from accessing and changing fields and methods of a class.
Heres an example of encapsulation in Java:
public 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;
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.setName("John");
person.setAge(30);
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
}
In this example, the Person
class has private variables name
and age
, and public getter and setter methods to access and modify these variables. The Main
class creates a Person
object and sets its name and age using the setter methods, and then prints out the values using the getter methods.