In Java, encapsulation is a mechanism of wrapping data and code together into a single unit, called a class. It is a fundamental principle of object-oriented programming (OOP) and is used to hide the implementation details of a class from its external users.
How to achieve Encapsulation in java
Encapsulation in Java is achieved by declaring the instance variables of a class as private and providing public getter and setter methods to access and modify those variables. This ensures that the state of the object can only be accessed and modified through these methods, which provide a layer of abstraction and control over the data.
Here’s an example of java encapsulation:
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;
}
}
In this example, the instance variables name
and age
are declared as private, which means they can only be accessed within the Person
class. The public getter and setter methods getName()
, setName()
, getAge()
, and setAge()
are provided to access and modify the variables, respectively.
By encapsulating the data in this way, we can ensure that the state of a Person
object is only accessed and modified in a controlled way, which makes the class more robust and less prone to errors