A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 木木三 中级黑马   /  2015-9-17 11:34  /  271 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. /*建立一个图形接口,声明一个面积函数。圆形和矩形都实现这个接口,并得出两个图形的面积。
  2. 注:体现面向对象的特征,对数值进行判断。
  3. 用异常处理。不合法的数值要出现"这个数值是非法的"提示,不再进行运算。
  4. 思路:
  5. 1,自定义异常,继承RuntimeException;
  6. 2,定义图形接口,定义抽象方法getArea();
  7. 3,定义矩形类实现图形接口,
  8.         定义成员变量及常量;
  9.         构造函数初始化:对成员变量进行判断,成员变量初始化;
  10.         复写父类接口的抽象方法getArea();
  11. */
  12. class NoValueException extends RuntimeException{
  13.         NoValueException(String message){
  14.                 super(message);
  15.         }
  16. }
  17. interface Shape{
  18.         abstract void getArea();
  19. }
  20. class Rec implements Shape{
  21.         private int len,wid;
  22.         Rec(int len ,int wid){
  23.                 if(len<=0 || wid<=0)
  24.                         throw new NoValueException("出现非法值");
  25.                 this.len = len;
  26.                 this.wid = wid;
  27.         }
  28.         public void getArea(){
  29.                 System.out.println(len*wid);
  30.         }
  31. }
  32. class Circle implements Shape{
  33.         private int radius;
  34.         public static final double PI = 3.14;//全局常量
  35.         Circle(int radius){
  36.                 if(radius<=0)
  37.                         throw new NoValueException("非法");
  38.                 this.radius = radius;
  39.         }
  40.         public void getArea(){
  41.                 System.out.println(radius*radius*PI);
  42.         }
  43. }
  44. class ExceptionTest{
  45.         public static void main(String[] args){
  46.                 Rec r = new Rec(3,4);
  47.                 r.getArea();
  48.                 System.out.println("over");
  49.         }
  50. }
复制代码

1 个回复

倒序浏览
复制粘贴
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马