编写球体类 长方体类 圆柱体类,他们是抽象类Graphics的子类用Java
时间: 2024-05-16 07:16:13 浏览: 13
好的,以下是基于抽象类Graphics的球体类、长方体类和圆柱体类的Java代码示例:
```java
// 抽象类Graphics定义
abstract class Graphics {
abstract double getArea(); // 获取图形的面积
abstract double getVolume(); // 获取图形的体积
}
// 球体类
class Sphere extends Graphics {
private double radius; // 球体的半径
public Sphere(double radius) {
this.radius = radius;
}
@Override
double getArea() {
return 4 * Math.PI * radius * radius;
}
@Override
double getVolume() {
return 4 * Math.PI * radius * radius * radius / 3;
}
}
// 长方体类
class Cuboid extends Graphics {
private double length; // 长方体的长
private double width; // 长方体的宽
private double height; // 长方体的高
public Cuboid(double length, double width, double height) {
this.length = length;
this.width = width;
this.height = height;
}
@Override
double getArea() {
return 2 * (length * width + length * height + width * height);
}
@Override
double getVolume() {
return length * width * height;
}
}
// 圆柱体类
class Cylinder extends Graphics {
private double radius; // 圆柱体的底面半径
private double height; // 圆柱体的高
public Cylinder(double radius, double height) {
this.radius = radius;
this.height = height;
}
@Override
double getArea() {
return 2 * Math.PI * radius * radius + 2 * Math.PI * radius * height;
}
@Override
double getVolume() {
return Math.PI * radius * radius * height;
}
}
```
以上代码中,抽象类Graphics定义了获取图形面积和体积的抽象方法,球体类、长方体类和圆柱体类都是Graphics类的子类,并实现了getArea()和getVolume()方法。在具体实现中,通过使用Java中的Math库进行数学计算,从而得到球体、长方体和圆柱体的面积和体积。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)