封装(数据的隐藏)
属性私有,get/set
作用:
1.提高程序的安全性,保护数据
2.隐藏代码的实现细节
3.统一接口
4.系统可维护增加了
package com.oop.demo03;
public class Student {
//属性私有
//提供一些可以操作这个属性的方法!
//提供一些public 的get. set方法
private String name;//名字
private int age;//年龄
private char sex;//性别
public String getName() {//get方法获取数据
return name;
}
public void setName(String name) {//set方法为数据设置值
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age>120||age<0){//不合法
this.age=-1;
}else {
this.age = age;
}
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
}
package com.oop;
import com.oop.demo03.Student;
public class Application {
public static void main(String[] args) {
Student s1 = new Student();
s1.setName("幻世蛮殇");
s1.setSex('男');
s1.setAge(21);
System.out.println(s1.getName());
System.out.println(s1.getSex());
System.out.println(s1.getAge());
}
}