(源码在上传的压缩包“【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();
}
}