编程:
利用接口做参数,写个计算器,能完成加减乘除运算。
(1)定义一个接口Compute含有一个方法int compute(int n, int m)。
(2)设计四个类分别实现此接口,完成加减乘除运算。
(3)设计一个类UseCompute,类中含有方法:public void useCom(Compute com, int one, int two),此方法能够用传递过来的对象调用computer方法完成运算,并输出运算的结果。
(4)设计一个主类Test,调用UseCompute中的方法useCom来完成加减乘除运算。
代码实现如下:
interface ICompute{
int compute(int n ,int m);
}
class Add implements ICompute {
public int compute(int n,int m) {
return n + m;
}
}
class Subtract implements ICompute{
public int compute(int n, int m) {
return n - m;
}
}
class Multiply implements ICompute{
public int compute(int n, int m) {
return n * m;
}
}
class Divide implements ICompute{
public int compute(int n, int m) {
if(m!=0){ //分母不能为零
return n/m;
}
System.out.println("错误输入");
return 0;
}
}
class UseCompute {
public void useCom(ICompute com, int one, int two) {
System.out.println(com.compute(one, two));
}
}
public class TestComputer{
public static void main(String[] args) {
UseCompute usecomputer = new UseCompute();
usecomputer.useCom(new Add(), 30, 7);
usecomputer.useCom(new Subtract(), 10, 8);
usecomputer.useCom(new Multiply(), 25, 4);
usecomputer.useCom(new Divide(), 66, 3);
}
}