【java学习记录】7.定义一个接口ArearInterface,其中包含一个方法,计算面积三角形、矩形、圆形的面积

(源码在上传的压缩包“【java学习记录】1-10的代码”中可看到,该压缩包可下载)

 

* 定义一个接口ArearInterface,其中包含一个方法,计算面积

 * 定义三个类:三角形、矩形、圆形,分别实现ArearInterface中的方法

 * 定义一个主类,将三角形和圆形的面积显示在屏幕上


ArearInterface 接口

public interface ArearInterface {//接口,计算面积
public double Area();
}

Rectangle 矩形

public class Rectangle implements ArearInterface{//矩形
double length;//length:长 
double width;//widt:宽

//初始化
public Rectangle(double length,double width){
this.length=length;
this.width=width;
}

//计算矩形面积
public double Area(){
double areaRectangle=0;
areaRectangle=length*width;
return areaRectangle;
}

//输出数值
public void Display(){
System.out.println("矩形:");
System.out.println("长为:"+length+"\t宽为:"+width);
System.out.println("面积为:"+Rectangle.this.Area());
System.out.println();
}
}

Round 圆

public class Round implements ArearInterface{//圆
double radius;//radius:半径

//初始化
public Round(double radius){
this.radius=radius;
}

//计算圆形面积
public double Area(){
double areaRound=0;
areaRound=radius*radius*3.14;
return areaRound;
}

//输出数值
public void Display(){
System.out.println("圆形:");
System.out.println("半径为:"+radius);
System.out.println("面积为:"+Round.this.Area());
System.out.println();
}
}

Triangle 三角形

public class Triangle implements ArearInterface{//三角形
double hemline;//hemline:三角形底边 
double height;//height:三角形高

//初始化
public Triangle(double hemline,double height){
this.hemline=hemline;
this.height=height;
}

//计算三角形面积
public double Area(){
double areaTriangle=0;
areaTriangle=hemline*height/2;
return areaTriangle;
}

//输出数值
public void Display(){
System.out.println("三角形:");
System.out.println("底边为:"+hemline+"\t高为:"+height);
System.out.println("面积为:"+Triangle.this.Area());
System.out.println();
}
}

Test 测试类

public class Test {
public static void main(String[] args){
Triangle t=new Triangle(2,3);
Rectangle r1=new Rectangle(10, 5);
Round r2=new Round(2);

t.Display();
r1.Display();
r2.Display();
}

}

  • 22
    点赞
  • 88
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值