定义一个接口 Compute,该接口实现两个功能,第一个为 sum(),实现两个数的相加,返回值为 int,第二个为 max(),比较两个数的大小,携带两个参数,类型为 int,返回值为 int。 定义一个公开的 ComputeClass 类并实现 Compute 接口,有两个属性,分别表示两个数,类型为 int。 类中有一个有参构造器,有实现接口类的两个方法,两个方法分别返回两数相加之和和两数中的最大值。
时间: 2023-10-28 11:04:27 浏览: 54
可以这样实现:
```java
public interface Compute {
int sum(int a, int b);
int max(int a, int b);
}
public class ComputeClass implements Compute {
private int num1;
private int num2;
public ComputeClass(int num1, int num2) {
this.num1 = num1;
this.num2 = num2;
}
@Override
public int sum(int a, int b) {
return a + b;
}
@Override
public int max(int a, int b) {
return a > b ? a : b;
}
}
```
使用方式如下:
```java
ComputeClass compute = new ComputeClass(10, 20);
int sumResult = compute.sum(10, 20); // 30
int maxResult = compute.max(10, 20); // 20
```
相关问题
(1)定义一个接口Compute含有一个方法int computer(int n, int m)
Sure! 这里是定义一个名为Compute的接口,包含一个名为computer的方法,该方法接受两个整数作为参数并返回一个整数。以下是该接口的代码示例:
```java
public interface Compute{
int computer(int n, int m);
}
```
希望这能解决您的问题!如果您有任何其他问题,请继续问我。
定义一个接口Compute,声明计算周长calgirth()和面积calarea ()的方法,然后定义一个长方形类Rect和圆类Circle,两个类都实现接口Compute
// 定义接口Compute
interface Compute {
double calgirth(); // 计算周长
double calarea(); // 计算面积
}
// 定义长方形类Rect
class Rect implements Compute {
private double length;
private double width;
// 构造函数
public Rect(double length, double width) {
this.length = length;
this.width = width;
}
// 实现接口Compute中的方法
public double calgirth() {
return (length + width) * 2;
}
public double calarea() {
return length * width;
}
}
// 定义圆类Circle
class Circle implements Compute {
private double radius;
// 构造函数
public Circle(double radius) {
this.radius = radius;
}
// 实现接口Compute中的方法
public double calgirth() {
return 2 * Math.PI * radius;
}
public double calarea() {
return Math.PI * radius * radius;
}
}
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![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)