繁体   English   中英

一个接口在 JAVA 中可以有非抽象方法吗?

[英]An Interface can have non-abstract mehod in JAVA?

在这里我发现一个接口可以有非抽象方法。 我对吗? 这是一个示例。在这段代码中,我创建了一个名为 A 的接口并实现了一个名为 show() 的非抽象方法。 那可能吗?

interface A{
    public abstract void display();
    default void show(){
        System.out.println("sHOW");
    }
}

public class Test 
{
    public static void main (String[]args) 
    {
        A i ;
        i = () -> System.out.println("Display");

        i.display();
        i.show();
    } 
}

接口的思想是有抽象的方法,就像人与人之间的契约。

在 Java 8 中,您可以使用default为该方法添加默认行为。

同样在 Java 8 中,您可以添加 static 方法。

从 Java 9 您可以定义私有方法。

Java 8 引入了接口中方法的“默认”实现的概念。 其动机是减少代码重复,因为类现在可以从接口“继承”方法实现,而不是被迫提供自己的方法实现。

这使得接口的工作方式与抽象类非常相似,但有一个重要的好处:您可以从多个接口继承内容。 使用抽象类,您只能从一个继承,这往往会产生很多限制。

In java 8, interface can have default method implementation, which is very similar to abstract class, but because the inheritance of java is single inheritance, if there is a class of template functions (for example, your show function) need to be used by the class, if you choose abstract class, then the target class can not inher other class, if you use the interface default method, the target only needs to implement the interface to use the show function. 这种做法在一定程度上是一种组合,而不是inheritance,它可以让目标class在其功能上有更多的选择性。

对的,这是可能的。 只要接口有一个单一的非defaultabstract方法( abstract关键字可以省略,因为它是隐式抽象的),那么接口可以用@FunctionalInteface注解,并且可以通过lambda表达式来表达。

最小的例子:

@FunctionalInterface
interface MyInterface {
    default void foo() {}
    void bar();
}
MyInterface myInterface = () -> {};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM