JAVA:利用接口做参数,写个计算器,能完成加减乘除运算。 您所在的位置:网站首页 计算器显示余数 JAVA:利用接口做参数,写个计算器,能完成加减乘除运算。

JAVA:利用接口做参数,写个计算器,能完成加减乘除运算。

2023-01-23 01:53| 来源: 网络整理| 查看: 265

        利用接口做参数,写个计算器,能完成加减乘除运算。

(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 nchu.demo; public interface Compute { public abstract int computer(int n,int m); }

 加减乘除

package nchu.demo; public class Add implements Compute{ public Add() { } @Override public int computer(int n, int m) { return m+n; } } package nchu.demo; public class Subtract implements Compute{ public Subtract() { } @Override public int computer(int n, int m) { return n-m; } } package nchu.demo; public class Multiply implements Compute{ public Multiply() { } @Override public int computer(int n, int m) { return m*n; } } package nchu.demo; public class Except implements Compute{ public Except() { } @Override public int computer(int n, int m) { return n/m; } }

使用计算器

package nchu.demo; public class UseCompute { public UseCompute() { } public void useCom(Compute com, int one, int two){ double i = com.computer(one,two); System.out.println("计算结果为:" + i); } }

Test

package nchu.demo; public class Test { public static void main(String[] args) { Compute a=new Add(); Compute b=new Subtract(); Compute c=new Multiply(); Compute d=new Except(); UseCompute Use = new UseCompute(); //加减乘除 Use.useCom(a,1,2); Use.useCom(b,1,2); Use.useCom(c,1,2); Use.useCom(d,1,2); } }



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有