这是我在研究函数式接口概念时遇到的一个例子。
interface Sayable{
void say();
}
public class MethodReference {
public static void saySomething(){
System.out.println("Hello, this is static method.");
}
public static void main(String[] args) {
// Referring static method
Sayable sayable = MethodReference::saySomething;
// Calling interface method
sayable.say();
}
}
这是打印“你好,这是静态方法。”在运行时的输出中。我的问题是,当我们调用 say() 方法(未实现)时,它如何打印输出
您可以将方法引用视为这样:
Sayable sayable = new Sayable() {
@Override
void say() {
// Grab the body of the method referenced by the method reference,
// which is the following:
System.out.println("Hello, this is static method.");
}
}
该方法引用有效,因为
- 目标类型是功能接口
Sayable
(您试图将结果存储到Sayable
类型);和
- the signature of the method reference to
saySomething()
matches the functional interface method say()
, that is, the parameters and the return type match1.
实施say()
的方法Sayable
称为变量的实例sayable
等于方法的主体方法参考指。
正如 JB Nizet 在评论中所说,say()
实际上is实施的。
1 A little detail: the word 'match' does not exactly mean 'are equal'. E.g. if saySomething()
returned an int
, it would still work, although the target type's only method defines the return type to be void
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)