What is Encapsulation | What is java encapsulation
The Meaning of Encapsulation is to make sure that sensitive data is hidden from the users, To achieve this, you must
- Declare class variables/attributes as private
- provide public get and set methods to access and updates the value of a private variable
Private variables can only be accessed within the same class (an outside class has no access to it ).
however, it is possible to access them if we provide public get and set methods.
It increase security of data
Encapsulation in java is a process of wrapping code and data together in to a single Unit,
for example a capsule which is mixed of several medicines, we can create a fully encapsulated class in java by making all the data members of the class private,
now we can use getter and setter to set and get the data in it.
The java Bean class is the example of a fully encapsulated class.
Example: –
public class Main {
private String Name;
//getter
public String getName() {
return Name;
}
//setter
public void setName(String name) {
Name = name;
}
}