使用继承编写Java中圆的面积和圆柱体积及半径相等判定
下面是使用继承编写的 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 语句来判断两个圆的半径是否相等。
免责声明:
以上内容除特别注明外均来源于网友提问,创作工场回答,未经许可,严谨转载。