关闭

Test____求矩形和圆面积的小练习

标签: javainterface异常
560人阅读 评论(0) 收藏 举报
分类:

求矩形和圆的面积

矩形长宽,圆的半径不能为负,否则抛出异常

知识点:接口,多态,异常

细节:函数返回值非空时需要在方法体return返回值

interface Are
{
	public double getArea();
} 

class FeifaException extends RuntimeException
{
	FeifaException()
	{
		super();
	}
	FeifaException(String msg)
	{
		super(msg);
	}
}

class Rec implements Are
{
	private int length;
	private int weight;
	private double sum;
	Rec(int length,int weight)
	{
		if(length<=0 || weight<=0)
		{
			throw new FeifaException("数值非法!!!");
		}
		this.length=length;
		this.weight=weight;
	}
	public double getArea()
	{
		sum=length*weight;
		System.out.println("矩形面积为:"+sum);
		return sum;
	}
}

class Circle implements Are
{
	public static final double PI=3.14;
	private int radius;
	private double sum;
	Circle (int radius)
	{
		if (radius<=0)
		{
			throw new FeifaException("数值非法!!!");
		}
		this.radius = radius;
	}
	public double getArea()
	{
		sum = radius*radius*PI;
		System.out.println("圆的面积为:"+sum);
		return sum;
	}
}

class  AreDemo
{
	public static void main(String[] args) 
	{
		Are r=new Rec(3,4);
		r.getArea();
		
		Are c = new Circle(-5);
		c.getArea();
		
		System.out.println("Hello World!");
	}
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:88324次
    • 积分:1510
    • 等级:
    • 排名:千里之外
    • 原创:56篇
    • 转载:5篇
    • 译文:0篇
    • 评论:68条
    博客专栏
    最新评论