qcode
  • 创作工场专业版,一问多答!更智能、更完整、更原创
  • 这是一个超强内容创作平台,它会写文章、做设计、绘图、敲代码,有问必答!
🔥点击使用-免登录深度版🔥

使用继承编写Java中圆的面积和圆柱体积及半径相等判定

时间2023-06-20 17:28:25 提问来自 辽宁省铁岭市 的网友 分类创作 浏览344
下面是使用继承编写的 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 语句来判断两个圆的半径是否相等。

不满意?免费深度重写!

免责声明:
以上内容除特别注明外均来源于网友提问,创作工场回答,未经许可,严谨转载。

上一篇 《我的职业生涯规划书》内容制作指南 下一篇 发条橙 A Clockwork Orange影评