• 面向对象封装性的练习


     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 }

    运行结果:

  • 相关阅读:
    jqmodal遮罩层的实现
    让Editplus和SVN集成
    asp.net很有用的字符串操作类
    TCP socket编程
    Adroid: ProgressBar 的使用
    在想的事情......
    I'm new to CNBlogs!
    压力
    开心工作
    feature
  • 原文地址:https://www.cnblogs.com/yunqing/p/4788924.html
Copyright © 2020-2023  润新知