Encapsulation in Java
Encapsulation means enclosing some items inside a capsule or tube tablet.
In OOPs, encapsulation means binding data members and methods inside a single unit.
It also acts as a security shield for datas.
Imagine you need water, can you take it directly from your neighbour's house without permission ?
No. Right?
You will ask the neighbour and he will take and give the water.
Encapsulation is also similar to the above scenario.
In encapsulation,
- Variables and datas are hidden from other classes. We can access data from other class indirectly only through its defined getter functions if defined.
To achieve encapsulation,
- We can set data or variables as private to restrict direct access from other classes.
- We can define setter and getter methods as public to access the restricted variables or values if needed.
Example
class Accounts{
private String email;
private String password;
public void setEmail(String email){
this.email=email;
}
public void setPassword(String password){
this.password=password;
}
public String getEmail(){
return email;
}
}
public class SignUp{
public static void main(String args[]){
Accounts account=new Accounts();
account.setEmail("[email protected]");
account.setPassword("56894");
System.out.println(account.getEmail()+" is successfully signed up");
}
}
Try In EditorOutput
[email protected] is successfully signed up
It helps in hiding internal details of a class.
It also helps in increasing readability of a program.
We can set read-only(only getters) and write-only(only setters) if needed.