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

}

 

posted @ 2016-09-26 23:14  张好好  阅读(6717)  评论(0编辑  收藏  举报