封装详解
- 图片来自B站狂神说
-
关键词:private
-
作用:
- 提高程序的安全性,保护数据
- 隐藏代码实现细节
- 统一接口
- 系统可维护性增加
- 使用:
- 使用关键词private定义变量
- 若在main方法中想要使用该变量,需要使用set/get方法
- 在set方法中可对数据进行判断是否合理
package oop.Demo03;
public class Student {
/*
1. 提高程序的安全性,保护数据
2. 隐藏代码实现细节
3. 统一接口
4. 系统可维护性增加
*/
private String name;//姓名
private int id;//学号
private char sex;//性别
private int age;//年龄
public void setName(String name){
this.name = name;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
package oop;
import oop.Demo03.Student;
public class Application {
public static void main(String[] args) {
Student s1 = new Student();
s1.setName("xiaoming");
s1.setId(999999);
s1.setSex('Y');
s1.setAge(18);
System.out.println(s1.getName());
System.out.println(s1.getId());
System.out.println(s1.getSex());
System.out.println(s1.getAge());
}
}
快捷键:Alt+Insert 可用来建立set/get方法