欢迎访问大师范文AI写作助手,如没有想要的内容请与本站万能的AI助手联系。

java,Circle 类的属性是 radius,Cylinder 的属性是 length,用继承编写两个圆的面积,体积,以及两个圆半径长度相等的判定结果

分享 时间: 加入收藏 我要投稿 点赞
下面是使用继承编写的 Java 代码:

```java
class Circle {
protected double radius;

public Circle(double radius) {
this.radius = radius;
}

public double getArea() {
return Math.PI * radius * radius;
}
}

class Cylinder extends Circle {
private double length;

public Cylinder(double radius, double length) {
super(radius);
this.length = length;
}

public double getVolume() {
return getArea() * length;
}
}

public class Main {
public static void main(String[] args) {
Circle circle1 = new Circle(5);
Circle circle2 = new Circle(7);

System.out.println("Circle 1 area: " + circle1.getArea());
System.out.println("Circle 2 area: " + circle2.getArea());

Cylinder cylinder1 = new Cylinder(5, 10);
Cylinder cylinder2 = new Cylinder(7, 15);

System.out.println("Cylinder 1 volume: " + cylinder1.getVolume());
System.out.println("Cylinder 2 volume: " + cylinder2.getVolume());

if (circle1.radius == circle2.radius) {
System.out.println("Circle 1 and Circle 2 have the same radius.");
} else {
System.out.println("Circle 1 and Circle 2 have different radii.");
}
}
}
```

在上面的代码中,我们定义了一个 `Circle` 类和一个 `Cylinder` 类,其中 `Cylinder` 类继承自 `Circle` 类。`Circle` 类有一个 `radius` 属性和一个 `getArea()` 方法,用于计算圆的面积。`Cylinder` 类有一个 `length` 属性和一个 `getVolume()` 方法,用于计算圆柱的体积。在 `Main` 类中,我们创建了两个圆和两个圆柱,并分别计算了它们的面积和体积。最后,我们使用一个简单的 if 语句来判断两个圆的半径是否相等。

精选图文

221381
领取福利

微信扫码领取福利

java,Circle 类的属性是 radius,Cylinder 的属性是 length,用继承编写两个圆的面积,体积,以及两个圆半径长度相等的判定结果

微信扫码分享