(1)定义一个接口Compute含有一个方法int computer(int n,int m); (2)设计四个类分别实现此接口,完成+-*/运算 (3)设计一个类UseCompute,含有方法: p...
时间: 2024-03-07 10:47:57 浏览: 82
好的,我理解你的问题了。
以下是我的回答:
1. 首先定义Compute接口:
```java
public interface Compute {
int computer(int n, int m);
}
```
2. 接着设计四个类实现Compute接口,分别完成加、减、乘、除运算:
```java
public class Add implements Compute {
@Override
public int computer(int n, int m) {
return n + m;
}
}
public class Subtract implements Compute {
@Override
public int computer(int n, int m) {
return n - m;
}
}
public class Multiply implements Compute {
@Override
public int computer(int n, int m) {
return n * m;
}
}
public class Divide implements Compute {
@Override
public int computer(int n, int m) {
return n / m;
}
}
```
3. 接着设计一个UseCompute类,含有一个方法printResult(Compute compute, int n, int m),用于输出加、减、乘、除运算的结果:
```java
public class UseCompute {
public void printResult(Compute compute, int n, int m) {
int result = compute.computer(n, m);
System.out.println("Result: " + result);
}
}
```
4. 最后编写一个测试类进行测试:
```java
public class Test {
public static void main(String[] args) {
UseCompute useCompute = new UseCompute();
Compute add = new Add();
useCompute.printResult(add, 10, 5);
Compute subtract = new Subtract();
useCompute.printResult(subtract, 10, 5);
Compute multiply = new Multiply();
useCompute.printResult(multiply, 10, 5);
Compute divide = new Divide();
useCompute.printResult(divide, 10, 5);
}
}
```
输出结果如下:
```
Result: 15
Result: 5
Result: 50
Result: 2
```
阅读全文