
Circle类:
public class Circle {
private double radius;//半径
public Circle(){
radius = 1.0;
}
//
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;
}
}
Cylinder类:
public class Cylinder extends Circle{
private double length;//高
public Cylinder(){
length = 1.0;
}
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
//返回圆柱的体积
public double findVolume(){
// return Math.PI * getRadius() * getRadius() * getLength();
return super.findArea() * getLength();
}
@Override
public double findArea() {//返回圆柱的表面积
return Math.PI * getRadius() * getRadius() * 2 +
2 * Math.PI * getRadius() * getLength();
}
}
CylinderTest:
public class CylinderTest {
public static void main(String[] args) {
Cylinder cy = new Cylinder();
cy.setRadius(2.1);
cy.setLength(3.4);
double volume = cy.findVolume();
System.out.println("圆柱的体积为:" + volume);
// 没有重写findArea()时:
// double area = cy.findArea();
// System.out.println("底面圆的面积:" + area);
// 重写findArea()以后:
double area = cy.findArea();
System.out.println("圆柱的表面积:" + area);
System.out.println("******************");
Cylinder cy1 = new Cylinder();
double volume1 = cy1.findVolume();
System.out.println("圆柱的体积为:" + volume1);
}
}
输出:
圆柱的体积为:47.10504024792536
圆柱的表面积:72.57079029792422
******************
圆柱的体积为:3.141592653589793
这篇博客介绍了Java编程中如何创建Circle和Cylinder类来计算圆的面积、圆柱的体积和表面积。示例代码展示了如何通过构造函数设置半径和高度,以及如何调用方法计算相关几何属性。Cylinder类继承了Circle类,并重写了findArea()方法以计算圆柱的表面积。
2100

被折叠的 条评论
为什么被折叠?



