用面向对象的思想定义一个接口Area,其中包含一个计算面积的方法CalsulateArea(),然后设计MyCircle和MyRectangle两个类都实现这个接口中的方法CalsulateArea(),分别计算圆和矩形的面积,最后写出测试以上类和方法的程序
时间: 2023-03-07 13:16:22 浏览: 145
接口Area:
public interface Area {
double calsulateArea();
}MyCircle:
public class MyCircle implements Area {
private double radius;
public MyCircle(double radius) {
this.radius = radius;
}
@Override
public double calsulateArea() {
return Math.PI * radius * radius;
}
}MyRectangle:
public class MyRectangle implements Area {
private double length;
private double width;
public MyRectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double calsulateArea() {
return length * width;
}
}测试程序:
public class Test {
public static void main(String[] args) {
Area circle = new MyCircle(5);
Area rectangle = new MyRectangle(5, 6);
System.out.println("圆的面积为:" + circle.calsulateArea());
System.out.println("矩形的面积为:" + rectangle.calsulateArea());
}
}
阅读全文