Java基礎-繼承 利用接口做參數,寫個計算器,能完成+-*/運算


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);
        
        
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM