gpt4 book ai didi

java - 接口(interface)中定义的方法的 "default"实现是什么?

转载 作者:IT老高 更新时间:2023-10-28 11:33:43 28 4
gpt4 key购买 nike

在集合接口(interface)中,我找到了一个名为 removeIf() 的方法,其中包含它的实现。

default boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
boolean removed = false;
final Iterator<E> each = iterator();
while (each.hasNext()) {
if (filter.test(each.next())) {
each.remove();
removed = true;
}
}
return removed;
}

我想知道有没有办法在接口(interface)中定义方法体?
default 关键字是什么,它是如何工作的?

最佳答案

来自 https://dzone.com/articles/interface-default-methods-java

Java 8 introduces “Default Method” or (Defender methods) new feature, which allows developer to add new methods to the interfaces without breaking the existing implementation of these interface. It provides flexibility to allow interface define implementation which will use as default in the situation where a concrete class fails to provide an implementation for that method.

public interface A {
default void foo(){
System.out.println("Calling A.foo()");
}
}

public class ClassAB implements A {
}

当人们第一次听说新功能时,有一个关于默认方法的常见问题:

What if the class implements two interfaces and both those interfaces define a default method with the same signature?

举例说明这种情况:

public interface A {  
default void foo(){
System.out.println("Calling A.foo()");
}
}

public interface B {
default void foo(){
System.out.println("Calling B.foo()");
}
}


public class ClassAB implements A, B {

}

此代码编译失败,结果如下:

java: class Clazz inherits unrelated defaults for foo() from types A and B

为了解决这个问题,在 Clazz 中,我们必须通过覆盖冲突方法来手动解决它:

public class Clazz implements A, B {
public void foo(){}
}

但是如果我们想从接口(interface) A 调用方法 foo() 的默认实现而不是实现我们自己的呢?

可以如下引用A#foo():

public class Clazz implements A, B {
public void foo(){
A.super.foo();
}
}

关于java - 接口(interface)中定义的方法的 "default"实现是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18286235/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com