什么是“默认"?接口中定义的方法的实现? [英] What is the "default" implementation of method defined in an Interface?

查看:28
本文介绍了什么是“默认"?接口中定义的方法的实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In the Collection Interface I found a method named removeIf() that contains its implementation.

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;  
}  

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

I want to know if there is any way to define method body in an interface?
What is the default keyword and how does it work?

推荐答案

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

Java 8 引入了默认方法"或(Defender 方法)新功能,允许开发人员在不破坏这些接口的现有实现的情况下向接口添加新方法.它提供了允许接口定义实现的灵活性,该实现将在具体类无法为该方法提供实现的情况下用作默认值.

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 {
}

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

There is one common question that people ask about default methods when they hear about the new feature for the first time:

如果类实现了两个接口,并且这两个接口都定义了一个具有相同签名的默认方法怎么办?

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 {

}  

此代码无法编译,结果如下:

This code fails to compile with the following result:

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

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

To fix that, in Clazz, we have to resolve it manually by overriding the conflicting method:

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

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

But what if we would like to call the default implementation of method foo() from interface A instead of implementing our own.

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

It is possible to refer to A#foo() as follows:

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

这篇关于什么是“默认"?接口中定义的方法的实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆