Encapsulation
Java Encapsulation means binding object states(fields) and behavior (methods) together. Creating class is the best example of encapsulation. It basically has both implementation hiding and information hiding. Getters and setters can be used to access the private members of a class.
There are four fundamental OOP concepts in Java, Encapsulation is one of them, and the other three are Inheritance, Polymorphism, and Abstraction.
Wrapping the data and codes are called Encapsulation. Data contains variables, and code has methods. With the help of Encapsulation, we can hide the class variables from other classes, and the variable can be used by that particular class only. That is why encapsulation is also known as data hiding.
Keypoints
- By using private keywords, we can encapsulate the data.
- For modification in variables, we can declare the public getter and setter function.
- With encapsulation, a class has total control of its variable and what its variables stores.
- The class can make itself read-only or write-only.
- Encapsulation is used to hide the implementation details from the users.
Declaring the variable as private can protect your data from outliers, and for modifying your private variable, you can use the getter and setter function within the class for inputs.
Advantages of Encapsulation
- Encapsulation is used to increase the flexibility, maintainability, and reusability of the code.
- We can adjust the permission for reading the code—for example, Read-only with the help of the getter method; if there is no such setter method, then the user can not change the variable value.
- The user can not be able to find the back implementation of the code.
Example :
Person.java
Com.knowledge2life
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String newName) {
this.name = newName;
}
}
Main.java
public class Main {
public static void main(String[] args) {
Person myObj = new Person();
myObj.name = "Knowledge2life";
System.out.println(myObj.name);
}
}
OUTPUT: