[基础题]2.(*)利用接口做参数,写个计算器,能完成加减乘除运算。
生活随笔
收集整理的這篇文章主要介紹了
[基础题]2.(*)利用接口做参数,写个计算器,能完成加减乘除运算。
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
/*2.(*)利用接口做參數,寫個計算器,能完成加減乘除運算。
(1)定義一個接口Compute含有一個方法int computer(int n, int m)。
(2)設計四個類分別實現此接口,完成加減乘除運算。
(3)設計一個類UseCompute,類中含有方法:public void useCom(Compute com, int one, int two),此方法能夠用傳遞過來的對象調用computer方法完成運算,并輸出運算的結果。
(4)設計一個主類Test,調用UseCompute中的方法useCom來完成加減乘除運算
(1)定義一個接口Compute含有一個方法int computer(int n, int m)。
(2)設計四個類分別實現此接口,完成加減乘除運算。
(3)設計一個類UseCompute,類中含有方法:public void useCom(Compute com, int one, int two),此方法能夠用傳遞過來的對象調用computer方法完成運算,并輸出運算的結果。
(4)設計一個主類Test,調用UseCompute中的方法useCom來完成加減乘除運算
*/
package HomeWork_10; public class Test_02 {//(4)public static void main(String[] args) {UseCompute uc = new UseCompute();Add s1 = new Add();Sub s2 = new Sub();Mul s3 = new Mul();Div s4 = new Div();System.out.print("和:");uc.useCom(s1,4,2);System.out.print("差:");uc.useCom(s2,4,2);System.out.print("積:");uc.useCom(s3,4,2);System.out.print("商:");uc.useCom(s4,4,2);} }interface Compute{//(1)接口int compute(int n,int m); }class Add implements Compute{//(2)public int compute(int n,int m){return n+m ;} }class Sub implements Compute{//(2)public int compute(int n,int m){return n-m ;} } class Mul implements Compute{//(2)public int compute(int n,int m){return n*m;} } class Div implements Compute{//(2)public int compute (int n,int m){return n/m;} }class UseCompute{//(3) Compute com就是Compute com =new Compute(); com.compute//new個com對象,對象調用方法,把one和two傳參進去public void useCom(Compute com, int one, int two){//方法名,傳參System.out.println(com.compute(one,two));} }總結
以上是生活随笔為你收集整理的[基础题]2.(*)利用接口做参数,写个计算器,能完成加减乘除运算。的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 继承练习 :开发一个系统时 需要对员工进
- 下一篇: [基础题] 3、设计一个交通工具抽象类,