1、利用接口做参数,写个计算器,能完成+-*/运算
(1)定义一个接口Compute含有一个方法int computer(int n,int m);
(2)设计四个类分别实现此接口,完成+-*/运算
(3)设计一个类UseCompute,含有方法: public void useCom(Compute com, int one, int two)
此方法要求能够:1.用传递过来的对象调用computer方法完成运算
2.输出运算的结果
(4)设计一个测试类,调用UseCompute中的方法useCom来完成+-*/运算
定义一个接口Compute含有一个方法int computer(int n,int m);
package 课堂实践;
public interface Computer {
public int computer(int n,int m);
}
设计四个类分别实现此接口,完成+-*/运算
//加法运算
package 课堂实践;
public class plus implements Computer {
public int computer(int n,int m) {
return n+m;
}
}
//减法运算
package 课堂实践;
public class plus implements Computer {
public int computer(int n,int m) {
return n-m;
}
}
//乘法运算
package 课堂实践;
public class plus implements Computer {
public int computer(int n,int m) {
return n*m;
}
}
//除法运算
package 课堂实践;
public class plus implements Computer {
public int computer(int n,int m) {
return n/m;
}
}
设计一个类UseCompute,含有方法: public void useCom(Compute com, int one, int two)
此方法要求能够:1.用传递过来的对象调用computer方法完成运算
//设计一个类UseComputer
package 课堂实践;
public class UseComputer {
public void UseComputer(Computer com,int one, int two )
{
int x =com.computer(one, two);
System.out.println("运算的结果为:"+x);
}
}
设计一个测试类,调用UseCompute中的方法useCom来完成+-*/运算
//测试结果
package 课堂实践;
public class Test {
public static void main(String[] args) {
UseComputer uc=new UseComputer();
int one =20;
int two =2;
Computer plus=new plus();
Computer jian=new JIAN();
Computer cheng=new CHENG();
Computer chu=new CHU();
uc.UseComputer(plus, one, two);
uc.UseComputer(jian, one, two);
uc.UseComputer(cheng, one, two);
uc.UseComputer(chu, one, two);
}
}