超类 Circle派生了一个称为 Cylinder 的子类,如下方类图所示。研究子类 Cylinder 如何调用超类 Circle 的构造函数,并从超类继承和使用方法 getArea()。Circle 属性 radius:圆半径。 color:圆颜色。 构造方法 Circle():初始化属性。 public Circle(double radius)。 public Circle(double radius,String color)。 方法 两个属性的set和get方法。 getArea():返回圆的面积。 toString(): 返回Circle[radius=xxx,color=xxx]。 Cylinder 属性 height:圆柱的高。 构造方法 Cylinder():初始化属性。 Cylinder(double height)。 Cylinder(double radius,double height)。 Cylinder(double radius, double height,String color)。 方法 属性height的set和get方法。 getVolume():返回圆柱体的体积(圆柱体体积计算公式为底面积x高)。 题目要求 根据题目描述和类图,完成圆和圆柱类。 注:在main方法当中测试类中的属性、方法、构造器。
时间: 2023-11-27 17:51:25 浏览: 83
下面是 Circle 和 Cylinder 类的实现:
```java
public class Circle {
private double radius;
private String color;
public Circle() {
this.radius = 0;
this.color = "";
}
public Circle(double radius) {
this.radius = radius;
this.color = "";
}
public Circle(double radius, String color) {
this.radius = radius;
this.color = color;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public double getArea() {
return Math.PI * radius * radius;
}
@Override
public String toString() {
return "Circle[radius=" + radius + ", color=" + color + "]";
}
}
```
```java
public class Cylinder extends Circle {
private double height;
public Cylinder() {
super();
this.height = 0;
}
public Cylinder(double height) {
super();
this.height = height;
}
public Cylinder(double radius, double height) {
super(radius);
this.height = height;
}
public Cylinder(double radius, double height, String color) {
super(radius, color);
this.height = height;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getVolume() {
return getArea() * height;
}
@Override
public String toString() {
return "Cylinder[height=" + height + ", " + super.toString() + "]";
}
}
```
在 main 方法中,可以进行如下测试:
```java
public static void main(String[] args) {
Circle c1 = new Circle();
Circle c2 = new Circle(3.0);
Circle c3 = new Circle(2.0, "red");
System.out.println(c1);
System.out.println(c2);
System.out.println(c3);
Cylinder cy1 = new Cylinder();
Cylinder cy2 = new Cylinder(4.0);
Cylinder cy3 = new Cylinder(3.0, 5.0);
Cylinder cy4 = new Cylinder(2.0, 6.0, "blue");
System.out.println(cy1);
System.out.println(cy2);
System.out.println(cy3);
System.out.println(cy4);
System.out.println("The area of c3 is " + c3.getArea());
System.out.println("The volume of cy4 is " + cy4.getVolume());
}
```
输出结果:
```
Circle[radius=0.0, color=]
Circle[radius=3.0, color=]
Circle[radius=2.0, color=red]
Cylinder[height=0.0, Circle[radius=0.0, color=]]
Cylinder[height=4.0, Circle[radius=0.0, color=]]
Cylinder[height=5.0, Circle[radius=3.0, color=]]
Cylinder[height=6.0, Circle[radius=2.0, color=blue]]
The area of c3 is 12.566370614359172
The volume of cy4 is 75.39822368615503
```
阅读全文