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

  • 相关阅读:
    d3-tree 双向树
    .gitignore
    url正则匹配
    this 指向
    git 用法小总结
    心态崩了?
    内存溢出和内存泄漏的区别
    jQuery添加方法
    物理像素与逻辑像素
    服务器返回的status
  • 原文地址:https://www.cnblogs.com/zs6666/p/5911122.html
Copyright © 2020-2023  润新知