【7】利用接口做参数,写个计算器,能完成+-*/运算 定义一个接口Compute含有一个方法int computer(int n,int m);设计四个类分别实现此接口,完成+-*/运算 设计一个类UseCompute,含有方法: public void useCom(Compute com, int one, int two) 此方法要求能够:1.用传递过来的对象调用computer方法完成运算 2.输出运算的结果 设计一个测试类,调用UseCompute中的方法useCom来完成+-*/运算。
时间: 2023-05-25 15:07:00 浏览: 463
JAVA计算器可实现整数加减乘除运算
5星 · 资源好评率100%
接口Compute:
```
public interface Compute {
int computer(int n, int m);
}
```
减法类Subtract:
```
public class Subtract implements Compute {
@Override
public int computer(int n, int m) {
return n - m;
}
}
```
乘法类Multiply:
```
public class Multiply implements Compute {
@Override
public int computer(int n, int m) {
return n * m;
}
}
```
除法类Divide:
```
public class Divide implements Compute {
@Override
public int computer(int n, int m) {
return n / m;
}
}
```
UseCompute类:
```
public class UseCompute {
public void useCom(Compute com, int one, int two) {
int result = com.computer(one, two);
System.out.println("运算结果:" + result);
}
}
```
测试类Test:
```
public class Test {
public static void main(String[] args) {
UseCompute useCompute = new UseCompute();
int a = 5;
int b = 2;
// 减法计算
Compute subtract = new Subtract();
useCompute.useCom(subtract, a, b);
// 乘法计算
Compute multiply = new Multiply();
useCompute.useCom(multiply, a, b);
// 除法计算
Compute divide = new Divide();
useCompute.useCom(divide, a, b);
}
}
```
阅读全文