//建立一个图形接口,声明一个面积函数,圆形和矩形都实现这个接口,并得出两个图形的面积
//注意,体现面向对象的特征,对数值进行判断,用异常处理,不合法的数值要出现“这个数值//是非法的”提示,不再进行运算。
自己写的:
interface Tuxing
{
void mianJi();
}
class Yuanxing implements Tuxing
{
private double r;
Yuanxing(double r)
{
this.r=r;
}
public void mianJi()
{
try
{
if(r<0) throw new Exception();
}
catch(Exception e)
{
System.out.println("这个数值是非法的");
return;
}
double mj=3.14*r*r;
System.out.println("这个圆形的面积是"+mj);
}
}
class Juxing implements Tuxing
{
private double c;
private double k;
Juxing(double c,double k)
{
this.c=c;
this.k=k;
}
public void mianJi()
{
try
{
if(c<0||k<0) throw new Exception();
}
catch(Exception e)
{
System.out.println("这个数值是非法的");
return;
}
double mj=c*k;
System.out.println("这个矩形的面积是"+mj);
}
}
public classDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Yuanxingy=newYuanxing(-2);
y.mianJi();
}
老师写的