封装
例题:
//student类
public class Student {
//属性私有 get/set
private String name;
private int age;
private char sex;
//提供一些public的get、set方法
//get获得这个数据
public String getName() {
return this.name;
}
//set给这个属性赋值
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if(age<120 && age>0) {
this.age = age;
}else {
System.out.println("输入的年龄不合法!");
}
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
}
//实现类
/*
1、 提高程序的安全性,保护数据
2、隐藏代码实现细节
3、统一接口
4、系统可维护增加了
*/
//一个项目应该只存在一个main方法
public class Application {
public static void main(String[] args) {
Student stu = new Student();
stu.setName("xyz");
System.out.println(stu.getName());
stu.setAge(999);
System.out.println(stu.getAge