封装
属性私有,get/set方法
使用封装可以1.提高程序的安全性,保护数据
2.隐藏代码的实现细节
3.统一接口
4.系统可维护增加了
代码:
package com.study.封装;
public class Student {
private String name;
private int id;
private int age;
//get获得这个是数据
public String getName() {
return name;
}
//给这个数据赋值
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.study.封装;
public class Application {
public static void main(String[] args) {
Student student = new Student();
student.setName("啦啦");
System.out.println(student.getName());//啦啦
student.setAge(10);
System.out.println(student.getAge());//10
}
}