java如下定义圆柱体类Cylinder,在其中私有变量半径和高等信息。在主类App7_1中用get、set方法进行赋值,并在主类中输出圆柱体底面积和体积
时间: 2024-05-24 09:12:45 浏览: 85
forward_MAG_cylinder.zip_圆柱体 磁_水平圆柱体_磁异常_;Magnetic_;matlab
5星 · 资源好评率100%
// Cylinder.java
public class Cylinder {
private double radius; // 半径
private double height; // 高
// 构造方法
public Cylinder(double radius, double height) {
this.radius = radius;
this.height = height;
}
// 计算底面积
public double getArea() {
return Math.PI * radius * radius;
}
// 计算体积
public double getVolume() {
return getArea() * height;
}
// 获取半径
public double getRadius() {
return radius;
}
// 设置半径
public void setRadius(double radius) {
this.radius = radius;
}
// 获取高
public double getHeight() {
return height;
}
// 设置高
public void setHeight(double height) {
this.height = height;
}
}
// App7_1.java
public class App7_1 {
public static void main(String[] args) {
Cylinder cylinder = new Cylinder(2.0, 5.0);
System.out.println("底面积:" + cylinder.getArea());
System.out.println("体积:" + cylinder.getVolume());
cylinder.setRadius(3.0);
cylinder.setHeight(6.0);
System.out.println("底面积:" + cylinder.getArea());
System.out.println("体积:" + cylinder.getVolume());
}
}
阅读全文