java 中的compute的接口及其实现
一.问题的描述
(1) 定义接口Compute。
接口方法有:int sum( ),求两个整数的和;int max( ),求两个整数中较大的数。
(2) 定义ComputeClass类。
要求ComputeClass类实现Compute接口;具有int类型的两个私有属性a和b提供有参构造方法ComputeClass (int a, int b)。sum()方法返回属性a与b的和,max返回属性a和b中较大者。
import java.util.Scanner;
public class ComputeTester {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
ComputeClass cc = new ComputeClass(a,b);
System.out.println("两数之和为:" + cc.sum());
System.out.println("较大值为:" + cc.max());
}
}
/* 定义接口Compute */
interface Compute{
int sum();
int max();
}
/* 定义Compute接口的实现类ComputeClass */
class ComputeClass implements Compute {
private int a;
private int b;
public ComputeClass(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int sum() {
return a + b;
}
@Override
public int max() {
return a > b ? a : b;
}
}