package com.atguigu.exer;
public class Person {
private int age;
private String name;
public Person(){
age = 18;
}
public Person(String n,int a){
name = n;
age = a;
}
public void setAge(int a){
if(a < 0 || a > 130){
// throw new RuntimeException("传入的数据非法!");
System.out.println("传入的数据非法!");
return;
}
age = a;
}
public int getAge(){
return age;
}
//绝对不要这样写!!
// public int doAge(int a){
// age = a;
// return age;
// }
public void setName(String n){
name = n;
}
public String getName(){
return name;
}
}
package com.atguigu.exer;
/*
* 在PersonTest类中实例化Person类的对象b,
* 调用setAge()和getAge()方法,体会Java的封装性。
*
*/
public class PersonTest {
public static void main(String[] args) {
Person p1 = new Person();
// p1.age = 1;编译不通过
p1.setAge(12);
System.out.println("年龄为:" + p1.getAge());
// p1.doAge(122);
Person p2 = new Person("Tom", 21);
System.out.println("name = " + p2.getName() + ",age = " + p2.getAge());
}
}