(接口的定义与类实现接口)编写一个Java程序,在程序中定义一个接口 Shape,包含两个抽象方法,一个是计算面积 area(),一个计算体积volume(),再定义一个类 Cylinder,实现这个Shape接口,设计一个程序,输出面积
时间: 2024-03-01 19:53:15 浏览: 57
和体积的值。
```java
interface Shape {
double area();
double volume();
}
class Cylinder implements Shape {
private double radius;
private double height;
public Cylinder(double radius, double height) {
this.radius = radius;
this.height = height;
}
@Override
public double area() {
return 2 * Math.PI * radius * (radius + height);
}
@Override
public double volume() {
return Math.PI * radius * radius * height;
}
}
public class Main {
public static void main(String[] args) {
Cylinder cylinder = new Cylinder(2.0, 5.0);
System.out.println("Area: " + cylinder.area());
System.out.println("Volume: " + cylinder.volume());
}
}
```
输出:
```
Area: 94.24777960769379
Volume: 62.83185307179586
```
阅读全文