Learn to program the Java Tutorial package released, you are welcome to visit through the xuebiancheng8.com
The following is an analysis of the encapsulation in object-oriented, and what is encapsulation. First, segment code.
public class person{
String username;
int age;
}
Person p = new person ();
P.username= "Zhang San";
p.age=-10;
The above instantiation of a person object p, and then assignment, here we assign the age value to 10, here is obviously not correct, because the age can not be negative, then how to do it, here we will username,age these two properties to privatize, not let the outside can give him value. So the code becomes this way
public class person{
Private String username;
private int age;
Public String GetUserName () {
return username;
}
public void Setusername (String username) {
This.username = Username;
}
public int getage () {
return age;
}
public void Setage (int.) {
if (age<0) {
Age = 0;
}else{
This.age = age;
}
}
}
Person p = new person ();
P.setusername ("Zhangsan");
P.setage (-10);
So after the setter and getter method, the user if the assignment is negative, then his value is 0, which is the encapsulation, the property is privatized, and the setter and getter method is generated, in the future class if there are attributes, the general situation will be encapsulated.
Please visit xuebiancheng8.com for details.
The specific URL is
Http://xuebiancheng8.com/play/goodgoodstudy_92_daydayup.html
Learn the package of Java tutorials