封装的意义
-
封装
- 该露的露,该藏的藏
- 我们程序设计要追求“高内聚,低耦合”。高内聚就是类的内部数据操作细节自己完成,不允许外部干涉;低耦合:仅暴露少量的方法给外部使用。
- 封装(数据的隐藏)
- 通常,应禁止直接访问一个对象中数据的实际表示,而应通过操作接口来访问,这称为信息隐藏。
- 记住这句话就够了:属性私有,get/set
- 提高程序的安全性,保护数据
- 隐藏代码的实现细节
- 统一接口
- 系统可维护性增加了
ALT+insert
自动生成方法
package com.oop.demo04;
//类 private :私有
public class Student {
public static void main(String[] args) {
}
//学生包括:名字 学号 性别 学习()睡觉()
//属性私有
private String name; //名字
private int id; //学号
private char sex; //性别
private int age;//年龄
//提供一些可以操作这个属性的方法
//提供一些public的get、set方法
//get获得这个数据
public String getName(){
return this.name;
}
//set 给这个数值设置值
public void setName(String name){
this.name =name;
}
//alt+insert:可以自动生成方法
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) {
if (age>120||age<0){
this.age = 3;
}else {
this.age = age;
}
}
//学习()
//睡觉()
}
主函数
package com.oop;
import com.oop.demo04.Student;
//一个项目应该只有一个main方法
public class Application {
public static void main(String[] args) {
Student S1 = new Student();
S1.setName("小钟");
System.out.println(S1.getName());
S1.setAge(70);//不合法
System.out.println(S1.getAge());
}
}