1. (简答题) 利用接口做参数,写个计算器,能完成加减乘除运算 (1)定义一个接口Compute(10分)含有一个抽象方法computer(int n, int m)(10分) (2)设计四个类分别实现此接口,完成加、减、乘、除运算(40分) (3)设计一个类UseCompute(10分),可以测试实现接口的乘的方法(20分),并输出运算的结果
时间: 2024-01-13 08:04:25 浏览: 95
(1)Compute接口定义如下:
```java
public interface Compute {
int computer(int n, int m);
}
```
(2)加、减、乘、除四个类分别实现Compute接口,代码如下:
加法类Add:
```java
public class Add implements Compute {
@Override
public int computer(int n, int m) {
return n + m;
}
}
```
减法类Subtract:
```java
public class Subtract implements Compute {
@Override
public int computer(int n, int m) {
return n - m;
}
}
```
乘法类Multiply:
```java
public class Multiply implements Compute {
@Override
public int computer(int n, int m) {
return n * m;
}
}
```
除法类Divide:
```java
public class Divide implements Compute {
@Override
public int computer(int n, int m) {
if (m == 0) {
throw new IllegalArgumentException("除数不能为0");
}
return n / m;
}
}
```
(3)UseCompute类测试乘法方法并输出结果,代码如下:
```java
public class UseCompute {
public void testCompute(Compute compute, int n, int m) {
int result = compute.computer(n, m);
System.out.println(n + "和" + m + "的运算结果是:" + result);
}
public static void main(String[] args) {
UseCompute useCompute = new UseCompute();
Compute multiply = new Multiply();
useCompute.testCompute(multiply, 5, 3);
}
}
```
输出结果:
```
5和3的运算结果是:15
```
阅读全文