(接口的定义与类实现接口)编写一个Java程序,在程序中定义一个接口 Shape,包含两个抽象方法,一个是计算面积 area(),一个计算体积volume(),再定义一个类 Cylinder,实现这个Shape接口,设计一个程序,输出面积和体积;
时间: 2023-12-25 22:02:35 浏览: 35
接口的定义:
```
public interface Shape {
double area();
double volume();
}
```
Cylinder类的实现:
```
public class Cylinder implements Shape {
double radius;
double height;
public Cylinder(double radius, double height) {
this.radius = radius;
this.height = height;
}
public double area() {
return 2 * Math.PI * radius * (radius + height);
}
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("The area of the cylinder is: " + cylinder.area());
System.out.println("The volume of the cylinder is: " + cylinder.volume());
}
}
```
输出结果:
```
The area of the cylinder is: 94.24777960769379
The volume of the cylinder is: 62.83185307179586
```
阅读全文