zoukankan      html  css  js  c++  java
  • 面向对象封装性的练习

     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 }

    运行结果:

  • 相关阅读:
    leetcode167 Two Sum II
    leetcode18 4Sum
    leetcode15 three sum
    leetcode-1-Two Sum
    SQL优化——select
    Hadoop 集群搭建
    虚拟机中的两台主机怎么相互拷贝文件
    doker5
    docker4
    docker3
  • 原文地址:https://www.cnblogs.com/yunqing/p/4788924.html
Copyright © 2011-2022 走看看