day10-04-面向对象(异常-练习)
2020-05-23 本文已影响0人
姗婷
需求有一个圆形和长方形都可以获取面积。
对于面积如果出现非法的数值,视为是获取面积出现问题,问题通过异常来处理
现在对这个程序进行基本的设计
看正常流程代码try,看异常流程代码catch
class NoValueException extends RuntimeException
{
NoValueException(String msg)
{
super(msg);
}
}
interface Shape
{
void getArea();
}
class Rec implements Shape
{
private int len,wid;
Rec(int len,int wid) //throws NoValueException
{
if(len<=0||wid<=0)
throw new NoValueException("非法值");
this.len = len;
this.wid = wid;
}
public void getArea()
{
System.out.println(len*wid);
}
}
class Circle implements Shape
{
private int radius;
public static final double PI= 3.14;
Circle(int radius)
{
if(radius<=0)
throw new NoValueException("非法值");
this.radius = radius;
}
public void getArea()
{
System.out.println(radius*radius*PI);
}
}
class ExceptionTest1
{
public static void main(String[] args)
{
Rec r = new Rec(3,4);
r.getArea();
Circle c = new Circle(-8);
c.getArea();
}
}