java接口拓展方法
时间: 2023-08-04 07:19:22 浏览: 64
Java接口可以通过两种方式来拓展方法:
1. 默认方法
默认方法是指在接口中定义的带有默认实现的方法。它可以通过接口的实现类对象或者接口类型来调用。默认方法的实现可以在接口中直接给出,也可以在实现类中重写。这种方式可以在不破坏已有代码的情况下,给接口增加新的方法。
举个例子,假设我们有一个接口Animal:
```
public interface Animal {
void eat();
void run();
default void sleep() {
System.out.println("Animal is sleeping");
}
}
```
现在我们需要在Animal接口中增加一个新方法fly,我们可以采用默认方法的方式:
```
public interface Animal {
void eat();
void run();
default void sleep() {
System.out.println("Animal is sleeping");
}
default void fly() {
System.out.println("Animal is flying");
}
}
```
这样,已有的实现类不需要做任何修改,而新的实现类可以直接继承Animal接口并实现新的方法fly。
2. 静态方法
静态方法是指在接口中定义的带有 static 关键字的方法。它可以直接通过接口类型来调用,不需要实现类对象。静态方法不能被实现类继承或重写。这种方式可以在接口中增加一些工具方法或者帮助方法。
举个例子,假设我们有一个接口Utils:
```
public interface Utils {
static int add(int a, int b) {
return a + b;
}
static int sub(int a, int b) {
return a - b;
}
}
```
这样,我们可以直接通过接口类型来调用add和sub方法,不需要创建实现类对象:
```
int result = Utils.add(1, 2);
int result2 = Utils.sub(5, 3);
```
相关推荐
![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_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)