当前位置: 首页 > news >正文

【Java】—— Java面向对象进阶:继承小练习-Java中实现圆柱体类及其体积计算

目录

1. 定义圆类(Circle)

2. 定义圆柱体类(Cylinder)

3. 测试圆柱体类

4. 总结


        在Java中,我们可以通过面向对象的方式来模拟现实世界中的物体,比如圆柱体。本篇文章将通过一个简单的示例来展示如何定义一个圆柱体类(Cylinder),并计算其体积。此外,我们还将创建一个圆类(Circle)作为基类,因为圆柱体的底面本质上是一个圆。

根据下图实现类。在CylinderTest类中创建Cylinder类的对象,设置圆柱的底面半径和高,并输出圆柱的体积。

1. 定义圆类(Circle)

首先,我们需要定义一个圆类Circle,它包含圆的半径和计算圆面积的方法。

package exer5;  public class Circle {  private double radius;  // 无参构造函数,默认半径为1  public Circle() {  radius = 1;  }  // 带参数的构造函数  public Circle(double radius) {  this.radius = radius;  }  // 获取半径  public double getRadius() {  return radius;  }  // 设置半径  public void setRadius(double radius) {  this.radius = radius;  }  // 计算圆的面积  public double findArea(){  return Math.PI * radius * radius; // 注意这里应该是半径的平方  }  
}

注意:在findArea方法中,我们使用了Math.PI来表示圆周率,并且圆的面积计算公式是πr²。

2. 定义圆柱体类(Cylinder)

        接着,我们定义一个圆柱体类Cylinder,它继承自Circle,并添加了圆柱体的高(length)属性和计算体积的方法。

package exer5;  public class Cylinder extends Circle{  private double length;  // 无参构造函数,默认半径为1,高也为1  public Cylinder() {  super(); // 调用父类的无参构造函数  length = 1;  }  // 带高的构造函数  public Cylinder(double length) {  super(); // 同样调用父类的无参构造函数  this.length = length;  }  // 带半径和高的构造函数  public Cylinder(double radius, double length) {  super(radius); // 调用父类的带参数构造函数  this.length = length;  }  // 获取高  public double getLength() {  return length;  }  // 设置高  public void setLength(double length) {  this.length = length;  }  // 计算圆柱体的体积  public double findVolume(){  return findArea() * length; // 圆柱体体积 = 圆的面积 * 高  }  
}

3. 测试圆柱体类

最后,我们创建一个测试类CylinderTest来实例化圆柱体对象,并计算其体积。

package exer5;  public class CylinderTest {  public static void main(String[] args) {  Cylinder cy = new Cylinder(2.3, 1.4); // 创建圆柱体对象,半径为2.3,高为1.4  System.out.println("圆柱的体积为:" + cy.findVolume()); // 输出圆柱体的体积  }  
}

4. 总结

        通过上述步骤,我们成功地定义了一个圆柱体类Cylinder,并通过继承圆类Circle来实现对圆柱体底面半径的管理。此外,我们还添加了计算圆柱体体积的方法,并通过测试类CylinderTest验证了代码的正确性。

        面向对象编程的一个重要特点是代码的复用性和可扩展性。通过继承机制,我们可以很容易地重用已有的代码,并通过添加新的属性和方法来扩展类的功能。在这个例子中,通过        


http://www.mrgr.cn/news/17430.html

相关文章:

  • git中的分支是什么?分支有哪些好处?如何建立分支?
  • 由键盘输入一个两位数,将其个位数与十位数互换后变成一个新的数,输出这个数。
  • PHP学习
  • 周记-2024年第35周8.26~9.1:但求有功,不求无过
  • 战略设计(Strategic Design)
  • 【编程底层思考】多线程编程中哪些行为和操作会导致线程让出cpu
  • Jenkins配置使用LDAP的用户和密码登录
  • VastBase——VPatch版本控制
  • 花店鲜花管理与推荐系统+Python+Django网页界面+管理系统+计算机课设
  • J.U.C Review - 白话Java内存模型
  • 9.1写论文
  • OpenCV入门
  • 中国各地级市全要素生产率(TFP)数据(1978-2022年)
  • 推荐10个开源且实用的大模型
  • python办公自动化:使用`Python-PPTX` 应用动画效果
  • 从Vue的Weex迁移到Rax Weex
  • UE5学习笔记20-给游戏添加声音
  • Python优化算法24——基于觅食生境选择的粒子群算法(FHSPSO)
  • jsmn输出
  • .net中的内存管理和垃圾回收