学习-java类和对象之类的组合之求圆柱体积
时间: 2023-04-24 22:02:15 浏览: 366
首先,我们需要定义一个圆柱类,包含圆的半径和高度两个属性。然后,我们可以在圆柱类中定义一个计算圆柱体积的方法,该方法使用圆的半径和高度计算圆柱体积。
具体实现如下:
1. 定义圆类
```
public class Circle {
private double radius; // 圆的半径
public Circle(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius; // 计算圆的面积
}
}
```
2. 定义圆柱类
```
public class Cylinder {
private Circle circle; // 圆柱的底面圆
private double height; // 圆柱的高度
public Cylinder(Circle circle, double height) {
this.circle = circle;
this.height = height;
}
public Circle getCircle() {
return circle;
}
public void setCircle(Circle circle) {
this.circle = circle;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getVolume() {
return circle.getArea() * height; // 计算圆柱体积
}
}
```
3. 使用圆柱类计算圆柱体积
```
public class Main {
public static void main(String[] args) {
Circle circle = new Circle(2.); // 创建底面圆
Cylinder cylinder = new Cylinder(circle, 3.); // 创建圆柱
double volume = cylinder.getVolume(); // 计算圆柱体积
System.out.println("圆柱体积为:" + volume);
}
}
```
输出结果为:
```
圆柱体积为:37.69911184307752
```
阅读全文