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

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

问题描述

在Collection Interface中,我找到了一个包含其实现的名为 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;  
}  

我想知道是否有任何方法可以在界面中定义方法体?

什么是默认关键字以及它是如何工作的?

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?

推荐答案

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天全站免登陆