Encapsulation


Encapsulation is practice in which 
-> We enclose something or binding together to protect the inner workings.
-> Expose things to outer world which are absolutely necessary.


For example :-

A Car Engine


You must be aware of car engine. It's internal design is complex. Now lets say car takes fuel as input and gives power as output. 
Do you care how engine works internally ?
Answer : No. And i dont care.

So here inner workings of engine are hidden and only fuel(Input), power(Output) is exposed to outer world. Now say tomorrow some mechanic changes the engine. It will not affect you as long as fuel and power are there.

That is encapsulation as inner working are hidden and only necessary things are exposed to you.

Tip:- Public API's use encapsulation mostly by taking certain inputs and providing fix output after processing. As long as inputs and outputs are fixed you will never get to know  how API is processing you inputs, that means API's inner workings are hidden from you and only inputs and outputs are exposed to you.

Implementation in Java
In Java a class implements encapsulation by using access modifiers ( Default, Public, Private, Protected). Here class encapsulate the instance variables and methods. It protects inner workings inside class by using private access modifier and expose necessary things to world by using public access modifier.

Code #

public class AdminUser
 {
private String username;
private String password;

public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

Here username and password are not exposed to everyone.