为什么带有 void 返回类型方法的函数接口接受任何返回类型方法? [英] Why does functional interface with void return-type method accept any return-type method?

查看:40
本文介绍了为什么带有 void 返回类型方法的函数接口接受任何返回类型方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有这个代码:

public class Test {
    public static Object foo() {
        System.out.println("Foo");
        return new Object();
    }

    public static void main(String[] args) {
        J j = Test::foo;
        j.m();
    }

}
interface J {
    void m();
}

此代码将起作用.关键是

And this code will work. The crucial line is

J j = Test::foo;

尽管 interface J 声明它有一个 void 函数,Test::foo 返回一个 Object.

Although interface J declares it has a void function, Test::foo returns an Object.

虽然我们不能在实现接口时覆盖方法(这是显而易见的).这只在接口的方法为void时有效,否则代码不会被编译.有人能说出为什么这会以这种方式工作吗?:D

While we can't override method while implementing interface (which is obvious). This works only when interface's method is void, otherwise the code won't be compiled. Could someone tell why does this work in the way it works? :D

推荐答案

尽管 interface J 声明它有一个 void 函数,Test::foo 返回一个 Object.

Although interface J declares it has a void function, Test::foo returns an Object.

Test::foo 返回一些东西是不准确的.在不同的上下文中,它可能意味着不同的东西.

It's inaccurate to say that Test::foo returns something. In different contexts, it could mean different things.

Supplier<Object>  a = Test::foo;
J                 b = Test::foo;
Runnable          c = Test::foo;

更准确地说,Test::foo 可以代表 目标类型 函数方法,其返回voidObject.

It's more accurate to say that Test::foo can represent a target type the functional method of which returns either void or Object.

这是一个表达式的例子声明 (jls-14.8).

如果目标类型的函数类型有一个 void 返回,那么 lambda 体要么是语句表达式(§14.8)或一个空兼容块(§15.27.2).
...
通过对表达式求值来执行表达式语句;如果表达式有值,该值将被丢弃.

If the target type's function type has a void return, then the lambda body is either a statement expression (§14.8) or a void-compatible block (§15.27.2).
...
An expression statement is executed by evaluating the expression; if the expression has a value, the value is discarded.

这篇关于为什么带有 void 返回类型方法的函数接口接受任何返回类型方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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