Java 接口调用接口方法
时间: 2023-10-08 12:11:40 浏览: 83
在 Java 中,接口可以定义方法,而实现类可以实现接口,并实现接口中定义的方法。如果一个接口中的方法需要调用另一个接口中的方法,可以通过以下步骤实现:
1. 让实现类同时实现两个接口。
2. 在实现类中实现第一个接口中的方法,并在方法中调用第二个接口中的方法。
3. 在第二个接口的实现类中实现该接口中的方法。
以下是一个示例代码:
```
interface Interface1 {
void method1();
}
interface Interface2 {
void method2();
}
class ImplementClass implements Interface1, Interface2 {
public void method1() {
method2(); // 调用 Interface2 中的方法
}
public void method2() {
System.out.println("Interface2 中的方法");
}
}
class Interface2Impl implements Interface2 {
public void method2() {
System.out.println("Interface2Impl 中的方法");
}
}
public class Main {
public static void main(String[] args) {
ImplementClass impl = new ImplementClass();
impl.method1(); // 输出 "Interface2Impl 中的方法"
}
}
```
在上面的代码中,ImplementClass 实现了 Interface1 和 Interface2 接口,并在 method1() 方法中调用了 Interface2 中的 method2() 方法。在 main() 方法中,实例化了 ImplementClass 类并调用了 method1() 方法,最终输出了 "Interface2Impl 中的方法"。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)