上机课的一道实验,就直接在写在博客上了,题目如下:
定义一个接口Area,其中包含一个计算面积的抽象方法calculateArea(), 然后设计Circle和Recaangle两个类都实现这个接口中的方法calculateArea(),分别计算圆和矩形的面积。


public class Homework04 {
    public static void main(String[] args) {
        //测试MyCircle
        MyCircle mc = new MyCircle(2);
        double area1 = mc.calculateArea();
        System.out.println(String.format("%.3f", area1));
        //测试Myrectangle
        MyRectangle mr = new MyRectangle(2,3);
        double area2 = mr.calculateArea();
        System.out.println(area2);
    }
 
}
//接口Area
interface Area {
    public abstract double calculateArea();
}
//MyCircle类
class MyCircle implements Area{
    double radius;
    public MyCircle() {
        super();
    }
    public MyCircle(double radius) {
        super();
        this.radius = radius;
    }
    @Override
    public double calculateArea() {
        return Math.PI*Math.pow(radius, 2);
    }
}
//MyRectangle类
class MyRectangle implements Area{
    double length1;
    double length2;
    public MyRectangle() {
        super();
    }
    public MyRectangle(double length1,double length2) {
        super();
        this.length1 = length1;
        this.length2 = length2;
    }
    @Override
    public double calculateArea() {
        return length1*length2;
    }
}

运行结果

最后修改:2021 年 06 月 05 日 06 : 32 PM
如果觉得我的文章对你有用,请随意赞赏