/*父类的某方法中有异常,子类继承父类后,若子类中有覆盖父类中出现异常的方法
则子类的方法异常只能是父类方法异常的子集
若父类没有异常方法,而子类中有异常出现,子类不能抛(throws),只能在子类方法内解决异常
*/
//需求:获取图形面积,若面积数值非法,则为异常
//异常也可封装,异常处理代码与正常流程相分离
class IllegalException extends RuntimeException
{
IllegalException(String msg)
{
super(msg);
}
}
interface Shape
{
public void getArea();
}
class Rec implements Shape
{
private double len,wid;
Rec(double len,double wid)throws IllegalException
{
if(len<0||wid<0)
throw new IllegalException("长或者宽不符合要求");
this.len=len;
this.wid=wid;
}
public void getArea()
{
System.out.println(len*wid);
}
}
class Circle implements Shape
{
private double radius;
public static final double PI=3.14;
Circle(double radius)
{
if(radius<0)
throw new IllegalException("半径不合法");
this.radius=radius;
}
public void getArea()
{
System.out.println(radius*radius*PI);
}
}
class ShapeExceptionDemo
{
public static void main(String[] args)
{
// try
// {
Rec r=new Rec(3.0,4);
r.getArea();
Circle c=new Circle(-3);
c.getArea();
// }
// catch (IllegalException e)
// {
// System.out.println(e.toString());
// }
}
}