//学生类
public class Student {
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;
}
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;
}
}
}
public class Application {
/*
封装:高内聚,低耦合--->高内聚:类的内部操作细节自己完成,不允许外部干涉; 低耦合:仅暴露少量的方法给外部使用
封装(数据的隐藏):通常,应禁止直接访问一个对象中数据的实际表示,而应通过操作接口来访问,这称为信息隐藏
属性私有,get/set
1.提高程序的安全性,保护数据
2.隐藏代码的实现细节
3.统一接口
4.系统可维护增加了
*/
public static void main(String[] args) {
Student student = new Student();
student.setName("杜");
System.out.println(student.getName());//杜
student.setAge(990);//不合法
System.out.println(student.getAge());//3
}
}