package com.java.exer;
/*
* 封装性的基本使用练习
* 创建程序,在其中定义两个类:Person和PersoonTest类。
* 定义如:用setAge()设置人的合法年龄(0~130)
* 用getAge()返回人的年龄
*/
public class Person
{
private int age;
public void setAge(int a)
{
if (a < 0 || a > 130) {
// throw new RuntimeException("传入的数据非法!");
System.out.println("传入的数据非法!");
return;// 去掉else 此处可以return
} // else {
age = a;
// }
}
public int getAge()
{
return age;
}
// 以下写法错误
// public int doAge(int a)
// {
// age = a;
// return age;
// }
}
package com.java.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() + "岁");
}
}
有帮助到你的点赞、收藏、关注一下吧
需要更多教程,微信扫码即可
👆👆👆
别忘了扫码领资料哦【高清Java学习路线图】
和【全套学习视频及配套资料】