7、根据要求写代码: (1) 定义接口Shape,包括属性PI和求面积方法getArea() (2) 定义圆类Circle,实现接口Shape,包括属性半径radius,提供带参构造,重写接口的求面积方法,增加求周长的方法getPerimeter (3) 定义圆柱体类Cylinder,继承圆类Circle,增加高度属性height,提供带参构造,重写求面积的方法getArea,增加求体积的方法getVolume (4) 测试类中分别创建圆类和圆柱体类对象,调用各自的方法
时间: 2023-07-16 21:13:27 浏览: 128
(1) 定义接口Shape
```java
public interface Shape {
double PI = 3.14;
double getArea();
}
```
(2) 定义圆类Circle
```java
public class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return PI * radius * radius;
}
public double getPerimeter() {
return 2 * PI * radius;
}
}
```
(3) 定义圆柱体类Cylinder
```java
public class Cylinder extends Circle {
private double height;
public Cylinder(double radius, double height) {
super(radius);
this.height = height;
}
@Override
public double getArea() {
return 2 * super.getArea() + 2 * PI * getRadius() * height;
}
public double getVolume() {
return super.getArea() * height;
}
public double getHeight() {
return height;
}
}
```
(4) 测试类
```java
public class Test {
public static void main(String[] args) {
Circle circle = new Circle(3);
System.out.println("圆的面积:" + circle.getArea());
System.out.println("圆的周长:" + circle.getPerimeter());
Cylinder cylinder = new Cylinder(3, 5);
System.out.println("圆柱体的底面积:" + cylinder.getArea());
System.out.println("圆柱体的体积:" + cylinder.getVolume());
System.out.println("圆柱体的高度:" + cylinder.getHeight());
}
}
```
阅读全文