您的位置:首页 > 编程语言 > Java开发

java 接口练习题4

2016-05-26 17:18 323 查看
利用接口做参数,写个计算器,能完成+-*/运算

(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来完成+-*/运算

public interface Compute {
int computer(int n,int m);

}


public class Jiafa implements Compute {

@Override
public int computer(int n, int m) {
// TODO 自动生成的方法存根
return n+m;
}

}


public class Jianfa implements Compute {

@Override
public int computer(int n, int m) {
// TODO 自动生成的方法存根
return n-m;
}

}


public class Chengfa implements Compute {

@Override
public int computer(int n, int m) {
// TODO 自动生成的方法存根
return n*m;
}

}


public class Chufa implements Compute {

@Override
public int computer(int n, int m) {
// TODO 自动生成的方法存根
return n/m;
}

}


public class UseCompute {
public void useCom(Compute com, int one, int two)
{
System.out.println(com.computer(one, two));
}

}


public class Ceshi {

public static void main(String[] args) {
// TODO 自动生成的方法存根

UseCompute u=new UseCompute();
System.out.print("3+5=");
u.useCom(new Jiafa(), 3, 5);
System.out.print("8-2=");
u.useCom(new Jianfa(), 8, 2);
System.out.print("2*7=");
u.useCom(new Chengfa(), 8, 2);
System.out.print("36/6=");
u.useCom(new Chufa(), 36, 6);
}

}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: