如果上述类不是通过继承机制,而是采用类的复用机制呢?例如,圆锥类的一个 成员变量为圆类的对象。将上述类按这种要求实现一遍。 java
时间: 2024-03-15 08:46:40 浏览: 172
以下是通过类的复用机制实现的代码:
1. 圆的类:
```java
public class Circle {
protected double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getPerimeter() {
return 2 * Math.PI * radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
}
```
2.1 环的类:
```java
public class Ring {
protected Circle outerCircle;
protected Circle innerCircle;
public Ring(double innerRadius, double outerRadius) {
this.outerCircle = new Circle(outerRadius);
this.innerCircle = new Circle(innerRadius);
}
public double getPerimeter() {
return outerCircle.getPerimeter() + innerCircle.getPerimeter();
}
public double getArea() {
return outerCircle.getArea() - innerCircle.getArea();
}
}
```
2.2 扇形的类:
```java
public class Sector {
protected Circle circle;
protected double angle;
public Sector(double radius, double angle) {
this.circle = new Circle(radius);
this.angle = angle;
}
public double getPerimeter() {
return circle.getPerimeter() * angle / 360;
}
public double getArea() {
return circle.getArea() * angle / 360;
}
}
```
2.3 圆锥的类:
```java
public class Cone {
protected Circle base;
protected double height;
public Cone(Circle base, double height) {
this.base = base;
this.height = height;
}
public double getSurfaceArea() {
double l = Math.sqrt(base.radius * base.radius + height * height);
return Math.PI * base.radius * l + Math.PI * base.radius * base.radius;
}
public double getVolume() {
return Math.PI * base.radius * base.radius * height / 3;
}
}
```
2.4 圆台的类:
```java
public class Frustum {
protected Cone cone1;
protected Cone cone2;
public Frustum(double bottomRadius, double topRadius, double height) {
Circle bottomCircle = new Circle(bottomRadius);
Circle topCircle = new Circle(topRadius);
this.cone1 = new Cone(bottomCircle, height);
this.cone2 = new Cone(topCircle, height);
}
public double getSurfaceArea() {
return cone1.getSurfaceArea() + cone2.getSurfaceArea() + Math.PI * (cone1.base.radius + cone2.base.radius) * Math.sqrt((cone1.base.radius - cone2.base.radius) * (cone1.base.radius - cone2.base.radius) + cone1.height * cone1.height);
}
public double getVolume() {
return cone1.getVolume() - cone2.getVolume();
}
}
```
阅读全文