利用接口做参数,写个计算器,能完成加减乘除运算。 (1)定义一个接口ICompute,含有方法int computer(int n,int m)。 (2)设计四个类分别实现此接口,完成加减乘除运算。 (3)设计一个类UseCompute,类中含有方法 public void useCom(Icompute com,int one,int two) 此方法能够用传递过来的对象调用computer方法完成运算,并输 出运算的结果。 (4)设计一个主类Test,调用UseCompute中的方法useCom来完成 加减乘除运算。java
时间: 2024-02-20 09:56:53 浏览: 10
下面是代码实现:
1. 接口 ICompute
```
public interface ICompute {
int computer(int n, int m);
}
```
2. 实现加减乘除四个类
```
public class Add implements ICompute {
@Override
public int computer(int n, int m) {
return n + m;
}
}
public class Subtract implements ICompute {
@Override
public int computer(int n, int m) {
return n - m;
}
}
public class Multiply implements ICompute {
@Override
public int computer(int n, int m) {
return n * m;
}
}
public class Divide implements ICompute {
@Override
public int computer(int n, int m) {
if (m == 0) {
throw new IllegalArgumentException("除数不能为0");
}
return n / m;
}
}
```
3. UseCompute 类
```
public class UseCompute {
public void useCom(ICompute com, int one, int two) {
int result = com.computer(one, two);
System.out.println(result);
}
}
```
4. Test 类
```
public class Test {
public static void main(String[] args) {
UseCompute useCompute = new UseCompute();
// 加法
ICompute add = new Add();
useCompute.useCom(add, 2, 3);
// 减法
ICompute subtract = new Subtract();
useCompute.useCom(subtract, 5, 3);
// 乘法
ICompute multiply = new Multiply();
useCompute.useCom(multiply, 2, 4);
// 除法
ICompute divide = new Divide();
useCompute.useCom(divide, 6, 2);
}
}
```