现有圆的抽象类或者接口: 2.1)实现圆的周长和面积的计算; 2.2)环,继承自圆。实现其面积的计算; 2.3)扇形,继承自圆。实现其周长和面积的计算; 2.4)圆锥,继承自圆。实现其表面积和体积的计算; 2.5)圆台,继承自圆锥。实现其表面积和体积的计算; 2.6)如果上述类不是通过继承机制,而是采用类的复用机制呢?例如,圆锥类的一个 成员变量为圆类的对象。将上述类按这种要求实现一遍。 java
时间: 2024-03-15 13:46:38 浏览: 147
Smith圆图阻抗匹配计算软件 V2.1
1. 圆的抽象类或接口:
```java
public abstract class Circle {
protected double radius; // 半径
public Circle(double radius) {
this.radius = radius;
}
public abstract double getPerimeter(); // 计算周长
public abstract double getArea(); // 计算面积
}
```
2.1 环类:
```java
public class Ring extends Circle {
protected double innerRadius; // 内半径
public Ring(double innerRadius, double outerRadius) {
super(outerRadius);
this.innerRadius = innerRadius;
}
@Override
public double getPerimeter() {
return 2 * Math.PI * (innerRadius + radius);
}
@Override
public double getArea() {
return Math.PI * (radius * radius - innerRadius * innerRadius);
}
}
```
2.2 扇形类:
```java
public class Sector extends Circle {
protected double angle; // 扇形角度
public Sector(double radius, double angle) {
super(radius);
this.angle = angle;
}
@Override
public double getPerimeter() {
return 2 * Math.PI * radius * angle / 360;
}
@Override
public double getArea() {
return Math.PI * radius * radius * angle / 360;
}
}
```
2.3 圆锥类:
```java
public class Cone extends Circle {
protected double height; // 高
public Cone(double radius, double height) {
super(radius);
this.height = height;
}
public double getSurfaceArea() {
return Math.PI * radius * (radius + Math.sqrt(radius * radius + height * height));
}
public double getVolume() {
return Math.PI * radius * radius * height / 3;
}
}
```
2.4 圆台类:
```java
public class Frustum extends Cone {
protected double topRadius; // 顶部半径
public Frustum(double bottomRadius, double topRadius, double height) {
super(bottomRadius, height);
this.topRadius = topRadius;
}
@Override
public double getSurfaceArea() {
double l = Math.sqrt((radius - topRadius) * (radius - topRadius) + height * height);
return Math.PI * (radius * radius + topRadius * topRadius + radius * l + topRadius * l);
}
@Override
public double getVolume() {
return Math.PI * height / 3 * (radius * radius + topRadius * topRadius + radius * topRadius);
}
}
```
2.5 类的复用,圆锥类中包含圆类的对象:
```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() {
return Math.PI * base.radius * (base.radius + Math.sqrt(base.radius * base.radius + height * height));
}
public double getVolume() {
return Math.PI * base.radius * base.radius * height / 3;
}
}
```
阅读全文