Java++圆类+Yuan+有属性+r,方法+area+(+)用于计算+S+圆。Yuan+Zhu+是+Yuan+的子类,新增属性+h+,方法+V+(+)用于计算+V+圆柱,有两个圆柱计算其体积
时间: 2024-01-09 15:23:14 浏览: 96
以下是Java++中圆类和圆柱类的实现:
1. 圆类(Yuan):
```java
public class Yuan {
private double r;
public Yuan(double r) {
this.r = r;
}
public double area() {
return Math.PI * r * r;
}
}
```
2. 圆柱类(YuanZhu)是圆类(Yuan)的子类,新增属性h,并添加方法V()用于计算圆柱的体积:
```java
public class YuanZhu extends Yuan {
private double h;
public YuanZhu(double r, double h) {
super(r);
this.h = h;
}
public double V() {
return area() * h;
}
}
```
如果有两个圆柱,可以分别创建两个YuanZhu对象,并调用V()方法计算它们的体积:
```java
YuanZhu yuanZhu1 = new YuanZhu(3.0, 4.0);
YuanZhu yuanZhu2 = new YuanZhu(5.0, 6.0);
double volume1 = yuanZhu1.V();
double volume2 = yuanZhu2.V();
System.out.println("Volume of cylinder 1: " + volume1);
System.out.println("Volume of cylinder 2: " + volume2);
```
这样就可以计算出两个圆柱的体积。
阅读全文