gpt4 book ai didi

java - 通过 lambda 表达式实现具有两个抽象方法的接口(interface)

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

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

我们可以引用下面的例子

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

那么主函数的结构会是什么来定义主函数本身的方法呢?

最佳答案

Lambda 表达式仅可用于 Eran 所说的功能接口(interface),但如果您确实需要接口(interface)中的多个方法,您可以将修饰符更改为 defaultstatic 和如有必要,在实现它们的类中覆盖它们。

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

继承

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

这里,I2继承了show1show2,因此不能作为函数式接口(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();
}

注释

为了确保你的接口(interface)是函数式接口(interface),你可以添加如下注解 @FunctionalInterface

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

@FunctionalInterface
interface I2 {
void show3();
}

关于java - 通过 lambda 表达式实现具有两个抽象方法的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36233477/

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