根据给出的抽象父类Shape及类层次关系说明图(类层次图),设计子类圆类Circle和子类圆柱体类Cylinder。定义类的无参数构造方法和有参数构造方法,覆盖父类方法满足子类要求,并按子类要求增加变量和相关方法。在各个类中增加main方法测试类,要求面积和体积的输出结果保留到小数点后两位。 类层次图:
时间: 2024-02-01 18:13:02 浏览: 59
```java
// Shape类
abstract class Shape {
public abstract double getArea();
public abstract double getVolume();
}
// Circle类
class Circle extends Shape {
private double radius;
public Circle() {
this.radius = 0;
}
public Circle(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
@Override
public double getVolume() {
return 0;
}
public static void main(String[] args) {
Circle circle = new Circle(2.5);
System.out.printf("Circle area: %.2f\n", circle.getArea());
}
}
// Cylinder类
class Cylinder extends Circle {
private double height;
public Cylinder() {
super();
this.height = 0;
}
public Cylinder(double radius, double height) {
super(radius);
this.height = height;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
@Override
public double getArea() {
return 2 * Math.PI * getRadius() * height + 2 * super.getArea();
}
@Override
public double getVolume() {
return super.getArea() * height;
}
public static void main(String[] args) {
Cylinder cylinder = new Cylinder(2.5, 3.0);
System.out.printf("Cylinder area: %.2f, volume: %.2f\n", cylinder.getArea(), cylinder.getVolume());
}
}
```
阅读全文
相关推荐



















