Java自学第三十四天

  今天对接口的一个练习题进行接口部分巩固。

  题目要求如下:

  利用接口做参数,写个计算器,能完成加减乘除运算。
(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来完成加减乘除运算。

  代码如下

interface Computer{
public int computer(int m,int n);
}
class Usecomputer{
private int a,b;
public void usecomputer(Computer com,int x,int y)
{
a=x;
b=y;
com.computer(a, b);
}
}
class add implements Computer{
private int a,b,result;
public int computer(int m,int n) {
a=m;
b=n;
result=a+b;
System.out.println(result);
return result;
}
}
class jian implements Computer{
private int a,b,result;
public int computer(int m,int n) {
a=m;
b=n;
result=a-b;
System.out.println(result);
return result;
}
}
class cheng implements Computer{
private int a,b,result;
public int computer(int m,int n) {
a=m;
b=n;
result=a*b;
System.out.println(result);
return result;
}
}
class chu implements Computer{
private int a,b,result;

public int computer(int m,int n) {
a=m;
b=n;
result=a/b;
System.out.println(result);
return result;
}
}
public class helloword {
public static void main(String[] args){
Usecomputer a=new Usecomputer();
a.usecomputer(new add(), 10, 5);
a.usecomputer(new jian(), 10, 5);
a.usecomputer(new cheng(), 10, 5);
a.usecomputer(new chu(), 10, 5);
}
}

分析整个过程,接口涉及到了一个方法用于赋值,Usecomputer用来给主函数调用方法,通过给主方法实例化类来调用方法,方法参数有Computer接口,用来调用不同的继承Computer的类的对接口中方法重写的方法,然后设计四个计算方法用来代表不同运算并且对接口方法进行重写,主函数通过Usecomputer的对象调用四次用来检验。(因为我的包的名称是helloword,所以主函数名称不是Test而是helloword)

  今天的习题算是比较简单的,今天做这道题的目的也是回顾接口的使用,毕竟接口是Java中十分重要的解决问题工具,解决这道题的过程中遇到的问题不大。

  明天我要继续寻找接口的习题进行练习,增加对接口的使用熟悉。

posted @ 2020-08-08 17:41  软工新人  阅读(187)  评论(0编辑  收藏  举报