题目:
创建程序。在其中定义两个类:Person和PersonTest类。
定义如下:用setAge()设置人的合法年龄。在PersonTest类种实例化Person类的对象b,调用setAge()和getAge()方法,体会Java的封装性
Person |
---|
-age:int |
+setAge(i:int) |
+getAge():int |
Person类:
public class Person {
private int age;
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;
// }
}
PersonTest类
public class PersonTest {
public static void main(String[] args) {
Person p1 = new Person();
// p1.age = 1;//编译不通过
p1.setAge(150);
System.out.println("年龄为:"+p1.getAge());
}
}
输出:
传入的数据非法!
年龄为:0