package oop.A_06_FZ;
//封装
/*步骤:
* 1.修改属性可见性private
* 2.创建共有的get/set读写方法
* 3.在get/set方法中加入控制语句
*/
public class Person {
private String name;//修改属性可见性private
private int age;//修改属性可见性private
//创建共有的get/set读写方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if(age>0) {// 在get/set方法中加入控制语句
this.age = age;
}
}
}
package oop.A_06_FZ;
public class PersonDemo {
public static void main(String[] args) {
Person per=new Person();
per.setName("admin");
per.setAge(10);//当setAge(-10)时因为方法里加了控制,会打印默认值0
System.out.println(per.getAge());
}
}