Encapsulation is one of the four fundamental OOP concepts.The ability to make changes in your implementation code without breaking the code of others who use your code is a key benefit of encapsulation. Let me give you an example: Lets say you have a class User, which holds User name and password
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class User{
private String userName;
private String password;
public String getUserName(){
return userName;
}
public void setUserName(String uname){
this.userName = uanem;
}
public String getPassword(){
return password;
}
public void setPassword(String pass){
this.password = pass;
}
}
And a lot of other programmers(may be 1000s) wrote programs that used your class such as:
1
2
User user = new User;
user.setUserName("theUserName");
Now your Manager announced some new rules:
- User name cannot be null.
- Password cannot be null.
- No one can set the user name less then 5 characters.
- No one can set the password less then 5 characters.
Just Think how easy it would be to make above changes by following the encapsulation rules. instead of changing all the code where your User
class is used you would change only setUserName(string)
& setPassword(string)
method as per code listed below.
1
2
3
4
5
6
7
8
9
10
11
public void setPassword(String pass){
//check password is not null;
//check password is more than 5 character long.
//set password.
}
public void setUserName(String uname){
//check user name is not null;
//check user name is more than 5 character long.
//set username.
}
You made the change only at one place and the the other 1000s of programmers code will adopt those rules automatically!!
Originally posted @ link