(1) 定义接口Compute。 接口方法有:int sum( ),求两个整数的和;int max( ),求两个整数中较大的数。 (2) 定义ComputeClass类。 要求ComputeClass类实现Compute接口;具有int类型的两个私有属性a和b提供有参构造方法ComputeClass (int a, int b)。sum()方法返回属性a与b的和,max返回属性a和b中较大者。
时间: 2023-12-10 16:42:42 浏览: 27
下面是Java代码实现:
```java
// 定义接口Compute
public interface Compute {
int sum(); // 求两个整数的和
int max(); // 求两个整数中较大的数
}
// 定义ComputeClass类,实现Compute接口
public class ComputeClass implements Compute {
private int a;
private int b;
// 有参构造方法
public ComputeClass(int a, int b) {
this.a = a;
this.b = b;
}
// 实现sum方法
public int sum() {
return a + b;
}
// 实现max方法
public int max() {
return a > b ? a : b;
}
}
```
使用示例:
```java
// 创建ComputeClass对象并调用sum和max方法
ComputeClass cc = new ComputeClass(10, 20);
System.out.println("sum: " + cc.sum()); // 输出:sum: 30
System.out.println("max: " + cc.max()); // 输出:max: 20
```
相关问题
1接口及其实现(20.0分) (1)定义接口Compute。 接口方法有: int sum( ),求两个整数的和; int max( ),求两个整数中较大的数。 (2)定义ComputeClass类。 要求ComputeClass类实现Compute接口;具有int类型的两个私有属性a和b提供有参构造方法ComputeClass(int a, int b)。sum()方法返回属性a与b的和,max返回属性a和b中较大者。
以下是Java语言的接口和实现:
```java
// 定义接口Compute
public interface Compute {
int sum(); // 求两个整数的和
int max(); // 求两个整数中较大的数
}
// 实现Compute接口的类ComputeClass
public class ComputeClass implements Compute {
private int a;
private int b;
// 有参构造方法
public ComputeClass(int a, int b) {
this.a = a;
this.b = b;
}
// 实现接口方法sum()
public int sum() {
return a + b;
}
// 实现接口方法max()
public int max() {
return (a > b) ? a : b;
}
}
```
在上述代码中,我们定义了一个接口`Compute`,其中包含了两个抽象方法`sum()`和`max()`。然后我们创建了一个实现了`Compute`接口的类`ComputeClass`,它有两个私有属性`a`和`b`,并且提供了一个有参构造方法用于初始化这两个属性。同时,`ComputeClass`类还实现了接口中的`sum()`和`max()`方法,分别用于求这两个属性的和和最大值。
(1)定义一个接口Compute含有一个方法int computer(int n, int m)
Sure! 这里是定义一个名为Compute的接口,包含一个名为computer的方法,该方法接受两个整数作为参数并返回一个整数。以下是该接口的代码示例:
```java
public interface Compute{
int computer(int n, int m);
}
```
希望这能解决您的问题!如果您有任何其他问题,请继续问我。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)