Encapsulation in Java is a concept that refers to the binding of data and methods that operate on that data within a single unit, such as a class. 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 helps to achieve data hiding, data security, and abstraction in Java.
To implement encapsulation in Java, you need to follow these steps:
- Declare the instance variables of a class as private, which means they can only be accessed within the class.
- Define public methods called getters and setters, which are used to retrieve and modify the values of the instance variables, respectively.
- Use the
this
keyword to refer to the current object within the class. - Use the class name and the constructor arguments (if any) to create an object of the class using the
new
keyword.
Here is an example of encapsulation in Java:
// A class that encapsulates the data and methods related to a person
class Person {
// private instance variables
private String name;
private int age;
// public getter method for name
public String getName() {
return name;
}
// public setter method for name
public void setName(String name) {
this.name = name;
}
// public getter method for age
public int getAge() {
return age;
}
// public setter method for age
public void setAge(int age) {
this.age = age;
}
}
// A class that tests the encapsulated class
public class Main {
public static void main(String[] args) {
// create an object of the Person class using the default constructor
Person person = new Person();
// set the values of the instance variables using the setter methods
person.setName("John") ;
person.setAge(30);
// get the values of the instance variables using the getter methods
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
}
The output of this program is:
Name: John
Age: 30