java使用接口计算两个正数a和b的算术平均值和几何平均值
时间: 2024-10-20 15:14:31 浏览: 14
在 Java 中,我们可以使用接口来定义方法的行为,而不需要指定具体的实现。首先,创建一个包含计算算术平均值和几何平均值方法的接口:
```java
// 创建名为AverageCalculator的接口
public interface AverageCalculator {
double calculateArithmeticMean(double a, double b);
double calculateGeometricMean(double a, double b);
}
```
然后,我们可以为这个接口提供两个类,它们实现了这两个方法,比如 `ArithmeticAverageCalculator` 和 `GeometricAverageCalculator`:
```java
// 实现算术平均值计算
public class ArithmeticAverageCalculator implements AverageCalculator {
@Override
public double calculateArithmeticMean(double a, double b) {
return (a + b) / 2;
}
// 接口并未规定geometricMean方法,这里是示例性的添加
@Override
public double calculateGeometricMean(double a, double b) {
return Math.sqrt(a * b);
}
}
// 实现几何平均值计算
public class GeometricAverageCalculator implements AverageCalculator {
@Override
public double calculateArithmeticMean(double a, double b) {
throw new UnsupportedOperationException("This class only calculates geometric average");
}
@Override
public double calculateGeometricMean(double a, double b) {
if (a <= 0 || b <= 0) {
throw new IllegalArgumentException("Positive numbers only for geometric mean");
}
return Math.pow(a * b, 0.5);
}
}
```
最后,你可以使用 `AverageCalculator` 接口来引用任意一个实现了它的类:
```java
public static void main(String[] args) {
AverageCalculator calculator = new ArithmeticAverageCalculator();
double arithmeticMean = calculator.calculateArithmeticMean(4.0, 6.0); // 输出结果
calculator = new GeometricAverageCalculator(); // 可以动态切换
double geometricMean = calculator.calculateGeometricMean(2.0, 3.0); // 输出结果
}
```
阅读全文