通过lambda表达式实现具有两个抽象方法的接口 [英] Implementing an interface with two abstract methods by a lambda expression

查看:233
本文介绍了通过lambda表达式实现具有两个抽象方法的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java 8中,引入了 lambda表达式 来帮助减少样板代码。如果界面只有一个方法,它可以正常工作。如果它由多个方法组成,那么这些方法都不起作用。我该如何处理多种方法?

In Java 8 the lambda expression is introduced to help with the reduction of boilerplate code. If the interface has only one method it works fine. If it consists of multiple methods, then none of the methods work. How can I handle multiple methods?

我们可以选择以下示例

public interface I1()
{
    void show1();
    void show2();
}

然后用于定义方法的主函数的结构是什么main本身?

Then what will be the structure of the main function to define the methods in the main itself?

推荐答案

Lambda表达式只能用于Eran所说的功能接口,但如果你真的需要接口中有多种方法,您可以将修饰符更改为 default static ,并在必要时在实现它们的类中覆盖它们。

Lambda expressions are only usable with functional interface as said by Eran but if you really need multiple methods within the interfaces, you may change the modifiers to default or static and override them within the classes that implement them if necessary.

public class Test {
    public static void main(String[] args) {
        I1 i1 = () -> System.out.println(); // NOT LEGAL
        I2 i2 = () -> System.out.println(); // TOTALLY LEGAL
        I3 i3 = () -> System.out.println(); // TOTALLY LEGAL
    }
}

interface I1 {
    void show1();
    void show2();
}

interface I2 {
    void show1();
    default void show2() {}
}

interface I3 {
    void show1();
    static void show2 () {}
}






继承



你不应该忘记继承的方法。


Inheritance

You shouldn't forget the inherited methods.

这里, I2 继承 show1 show2 因此不能成为功能界面。

Here, I2 inherits show1 and show2 and thus can not be a functional interface.

public class Test {
    public static void main(String[] args) {
        I1 i1 = () -> System.out.println(); // NOT LEGAL BUT WE SAW IT EARLIER
        I2 i2 = () -> System.out.println(); // NOT LEGAL
    }
}

interface I1 {
    void show1();
    void show2();
}

interface I2 extends I1 {
    void show3();
}






注释



为确保您的界面是功能界面,您可以添加以下注释 @FunctionalInterface

@FunctionalInterface <------- COMPILATION ERROR : Invalid '@FunctionalInterface' annotation; I1 is not a functional interface
interface I1 {
    void show1();
    void show2();
}

@FunctionalInterface
interface I2 {
    void show3();
}

这篇关于通过lambda表达式实现具有两个抽象方法的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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