Introduction to Java (10) - Encapsulation
Table of contents
Introduction to Java (10) - Encapsulation
encapsulation
benefit
- After encapsulation, you can only use the provided entrance when referencing, and the content inside cannot be changed, which has higher security
- It is very convenient to use a simple operation entrance -
A real "object" will be formed after encapsulation , a true independent body
- the encapsulated program can be reused, has strong adaptability, and can be used in any situation
step
- Therefore, to privatize attributes, use the private keyword to modify them. Private means private. All modified data can only be accessed in this class.
- Provide simple entrances to allow external access. There are two forms of access: reading get, modifying set
- set method naming rules: (example)
public void setAge(int a){ age=a; } - get method naming rules: (example) public void getAge(){ return age; }
Notice
- Getters and Setters can be generated through the source code
- Getter and Setter methods do not have the static keyword
- The calling method with static is: class name.Method name (actual parameters)
- The calling method without static is: reference.Method name (actual parameters) ginseng)
Sample code
class User {
private int age;
static String name="张三";
public void setAge(int age) {
if(age<20 || age>40)
System.out.println("抱歉您的年龄不适合我们的工作。非常抱歉!");
else {
this.age = age;
System.out.println("您的年龄是"+this.age+"岁,很高兴您能加入我们的队伍。");
}
}
public int getAge() {
return age;
}
}
public class Encapsulation{
public static void main(String[] args) {
User user = new User();
//不能访问user.age,是因为age的属性私有化了。
//System.out.println(user.age);
System.out.println(User.name);//类名.方法名
user.setAge(50);//引用.方法名
}
}