定义一个接口(Addable),里面定义一个抽象方法:add,用以求和 定义一个测试类(AddableDemo),在测试类中提供两个方法 一个方法是:useAddable(Addable a) 一个方法是主方法,在主方法中调用useAddable方法
时间: 2024-03-09 12:51:06 浏览: 22
好的,这是您的问题:
```java
// 定义接口 Addable
interface Addable {
int add(int a, int b);
}
// 定义测试类 AddableDemo
public class AddableDemo {
// 定义方法 useAddable,接收一个 Addable 类型的参数
public static void useAddable(Addable a) {
int sum = a.add(10, 20);
System.out.println("10 + 20 = " + sum);
}
// 主方法
public static void main(String[] args) {
// 调用 useAddable 方法,传入一个匿名内部类对象
useAddable(new Addable() {
@Override
public int add(int a, int b) {
return a + b;
}
});
}
}
```
这个代码定义了一个接口 `Addable`,其中包含一个抽象方法 `add`,用于求和。然后定义了一个测试类 `AddableDemo`,其中包含一个方法 `useAddable`,用于接收一个 `Addable` 类型的参数,并在方法内部调用 `add` 方法求和。主方法中调用了 `useAddable` 方法,传入一个匿名内部类对象,实现了 `Addable` 接口的 `add` 方法。
相关推荐
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)