38.利用接口做參數,寫個計算器,能完成+-*/運算
(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來完成+-*/運算
package hanqi; public interface Compute { int computer(int n,int m); }
package hanqi; public class Jia implements Compute { @Override public int computer(int n, int m) { // TODO 自動生成的方法存根 return n+m; } }
package hanqi; public class Jian implements Compute { @Override public int computer(int n, int m) { // TODO 自動生成的方法存根 return n-m; } }
package hanqi; public class Cheng implements Compute { @Override public int computer(int n, int m) { // TODO 自動生成的方法存根 return n*m; } }
package hanqi; public class Chu implements Compute { @Override public int computer(int n, int m) { // TODO 自動生成的方法存根 return n/m; } }
package hanqi; public class UseCompute { public void useCom(Compute com, int one, int two) { System.out.println(com.computer(one, two)); } }
package hanqi; public class TestCeshi { public static void main(String[] args) { UseCompute a =new UseCompute(); a.useCom(new Jia(), 2, 2); a.useCom(new Jian(), 2, 2); a.useCom(new Cheng(), 2, 2); a.useCom(new Chu(), 2, 2); } }