JAVA 封装的学习

 

 public static void main(String[] args) {
Student S1 = new Student();
String Ao = S1.getName();
S1.setName("敖晨光");
System.out.println(S1.getName());
S1.setAge(-1);
System.out.println(S1.getAge());

}
//属性私有
private String name;//姓名

private int id; //学号

private char sex; //性别

private int age;


//提供一些可以操纵这些属性的方法!
//提供一些public 的 set 和 get的方法
//get 获得数据
public String getName() {
return this.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 < 0 || age > 120) {
System.out.println("人才输入");
this.age = 3;
} else {
this.age = age;
}

}

//set 给这个数据设置值
public void setName(String name) {
this.name = name;


}


}
/*
1.提高程序的安全性,保护数据
2.隐藏代码的实现细节
3.统一接口
4.系统可维护增加了
*/

原文地址:https://www.cnblogs.com/acg-lbj/p/13237043.html