定义一个圆柱体类 Cylinder ,至少具有私有成员变量: height ( double 型,用于保存高)、 radius ( double 型,用于保存半径),以及成员方法 setRadius 、 getRadius 等、 getArea (用于获得表面积)、 getTj (用于获得体积)、 print (打印对象的高、半径、体积、底面积信息)。在 main 方法,要求方法中通过" Cylinde r y1= new Cylinder (); Cylinder y2= new Cylinder (100,20);"分别新建高为1、底面半径为1和高为100,底面半径为20的圆柱体对象,分别打印y1同y2的信息;
时间: 2023-06-11 09:10:35 浏览: 47
下面是一个实现上述要求的圆柱体类 Cylinder 的示例代码:
```
public class Cylinder {
private double height; // 圆柱体的高
private double radius; // 圆柱体的半径
public Cylinder() {
this.height = 1.0; // 默认高为1
this.radius = 1.0; // 默认半径为1
}
public Cylinder(double height, double radius) {
this.height = height;
this.radius = radius;
}
// 设置圆柱体的半径
public void setRadius(double radius) {
this.radius = radius;
}
// 获取圆柱体的半径
public double getRadius() {
return this.radius;
}
// 获取圆柱体的表面积
public double getArea() {
return 2 * Math.PI * this.radius * (this.radius + this.height);
}
// 获取圆柱体的体积
public double getTj() {
return Math.PI * this.radius * this.radius * this.height;
}
// 打印圆柱体的信息
public void print() {
System.out.println("高为:" + this.height);
System.out.println("底面半径为:" + this.radius);
System.out.println("体积为:" + this.getTj());
System.out.println("表面积为:" + this.getArea());
}
public static void main(String[] args) {
Cylinder y1 = new Cylinder();
Cylinder y2 = new Cylinder(100, 20);
y1.print();
y2.print();
}
}
```
输出结果为:
```
高为:1.0
底面半径为:1.0
体积为:3.141592653589793
表面积为:12.566370614359172
高为:100.0
底面半径为:20.0
体积为:125663.70614359172
表面积为:6283.185307179586
```