封装
封装详解
- “高内聚,低耦合”
高内聚就是类的内部数据操作细节自己完成,不允许外部干涉;
低耦合:仅暴露少量的方法给外部使用
-
封装(数据的隐藏)
通常,应禁止直接访问一个对象中数据的实际表示,而应通过操作接口来访问,这称为信息隐藏 -
属性私有,get/set
package com.oop.Demo04;
//类 private:私有
public class Student {
//属性私有、
private String name;
private int id;
private char sex;
private int age;
//提供一些可以操作这个属性的方法
//提供一些public的get、set方法
//获得这个数据
public String getName(){
return this.name;
}
//set给这个数据设置值
public void setName(){
this.name = name;
}
//alt + insert
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
/*
封装
1.提高程序的安全性,保护数据
2.隐藏代码的实现细节
3.统一接口
4.增加系统的可维护
*/
public class Application {
public static void main(String[] args){
Student s1 = new Student();
//判断是否是同一个方法:方法名、参数列表
s1.setName("李明");
System.out.println(s1.getName());
s1.setAge(8);
System.out.println(s1.getAge());
}
}

浙公网安备 33010602011771号