面向对象封装性的练习

 1 package com.cnblogs.exer;
 2 
 3 //1.创建程序在其中定义两个类,Person和TestPerson,设置如下:
 4 //用setAge设置人的合法年龄(0~130),用getAge返回人的年龄值
 5 //在TestPerson类中实例化Person类的对象b,调用setAge(),getAge()方法,体会Java的封装性
 6 
 7 public class TestPerson {
 8     public static void main(String[] args) {
 9         Person b=new Person();
10         b.setAge(-4);//执行抛出异常的语句。
11         System.out.println(b.getAge());
12     }
13 }
14 class Person{
15     private int Age;
16     
17     public void setAge(int a){
18         if(a>0 && a<130){
19             Age=a;
20         }
21         else{
22             //System.out.println("你输入的年龄不合法!");
23             //这种方法在输出不合法之后会给出一个年龄默认值,int型,所以为0
24             throw new RuntimeException("输入的数据有误!");
25             //自定义抛出一个异常
26         }
27     }
28     public int getAge(){
29         return Age;
30     }
31 }

运行结果:

面向对象封装性的练习