一、封装
- 该露的露,该藏的藏
- 我们程序设计要追求"高内聚,低耦合"。
- 高内聚:类的内部数据操作细节自己完成,不允许外部干涉
- 低耦合:仅暴露少量的方法给外部使用
- 封装(数据的隐藏)
- 通常,应禁止直接访问一个对象中数据的实际表示,而应通过操作接口来访问,这称为信息隐藏
-
记住这句话就够了:属性私有,get/set——快捷键:alt+insert
- 封装大多数时是对属性应用,对方法用的比较少(重点是对属性应用)
- 成员变量有四种修饰符Java面向对象:访问修饰符
-
private 私有的
-
package/friendly/default 不写
-
protected 受保护的
-
public 公共的
- 私有的 private 修饰符 跟 公用的 public 修饰符是对应的
- private 修饰符 不能像 public 修饰符 一样直接调用 Student 属性
- 提供一些可以操作属性的方法:public 的 get/set 方法
——get 获得这个数据(属性)——set 设置这个数据(属性) - 封装的作用:
- 提高程序的安全性,保护数据
- 隐藏代码的实现细节
- 统一接口(都是get/set)
- 系统的可维护性增加了
- 封装的实现步骤
- 第一步:属性私有化(private修饰符)
- 第二步:每个属性对外提供两个方法(get与set方法),可以在set方法中设立关卡来保证数据的安全性
-
代码(例)
- Student类(学生类)
public class Student {//学生类 //静态的属性---属性:名字、学号、性别 //动态的行为---方法:学习()、睡觉() //封装大多数时是对属性应用,对方法用的比较少(重点是对属性应用) //属性 //private 修饰符------私有 private String name;//名字 private int id;//学号 private char sex;//性别(男、女) private int age;//年龄(0~120) //private修饰符 不能像 public修饰符 一样直接调用 Student 属性 //提供一些可以操作属性的方法:public 的 get/set 方法 //get 获得这个数据(属性) //set 设置这个数据(属性) //快捷键:alt+insert //姓名 get/set public String getName() { return name; } public void setName(String name) { this.name = name; } //学号 get/set public int getId() { return id; } public void setId(int id) { this.id = id; } //性别 get/set public char getSex() { return sex; } public void setSex(char sex) { if(sex=='男' || sex=='女'){//合法性别 this.sex = sex; }else { System.out.print("未知"); } } //年龄 get/set public int getAge() { return age; } public void setAge(int age) { if (age<=120 && age>0){//合法年龄 this.age = age; }else { this.age = 0; } } //=========================================================================== //方法 public void study (){//学习() if (this.name==null){ }else { System.out.println(this.name+"在学习"); } } public void sleep (){ if (this.name==null){ }else { System.out.println(this.name+"在睡觉"); } } }
- Application类(总测试类)
/* 封装的作用: 1.提高程序的安全性,保护数据 2.隐藏代码的实现细节 3.统一接口(都是get/set) 4.系统的可维护性增加了 */ public class Application { public static void main(String[] args) { Student xiaoming = new Student(); xiaoming.setName("小明"); xiaoming.setAge(24); xiaoming.setSex('男'); xiaoming.setId(100001); System.out.println(xiaoming.getName());//小明 System.out.println(xiaoming.getAge());//24 System.out.println(xiaoming.getSex());//男 System.out.println(xiaoming.getId());//100001 xiaoming.study();//小明在学习 xiaoming.sleep();//小明在睡觉 } }
- Student类(学生类)