设计图形Shape接口及其子类圆Circle和矩形Rectangle类。接口中声明求图形面积的方法getArea,并两个子类中实现。再定义测试类Test,实现圆和矩形面积的输出。(接口)
时间: 2023-12-10 13:40:28 浏览: 84
设计一个Shape接口和它的两个实现类Square和Circle,要求如下
下面是Java代码实现:
```
// Shape接口
public interface Shape {
double getArea();
}
// 圆类
public class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
// 矩形类
public class Rectangle implements Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
@Override
public double getArea() {
return length * width;
}
}
// 测试类
public class Test {
public static void main(String[] args) {
Circle c = new Circle(5);
System.out.println("圆的面积为:" + c.getArea());
Rectangle r = new Rectangle(3, 4);
System.out.println("矩形的面积为:" + r.getArea());
}
}
```
阅读全文