gpt4 book ai didi

java-8 - 将 "pass a reference"传递给与抽象方法的参数列表匹配的方法时,java 8 如何在内部求值?

转载 作者:行者123 更新时间:2023-12-01 13:17:53 25 4
gpt4 key购买 nike

我一直在使用 Java 8 函数式接口(interface),当我开始执行下面的代码时,我注意到一些不寻常的事情。

interface Carnivore{

default int calories( List<String> food)
{
System.out.println("=======line ABC ");
return food.size() * 100;
}

int eat(List<String> foods);

}

class Tiger implements Carnivore{

public int eat(List<String> foods)
{
System.out.println("eating "+ foods);

return foods.size();
}
}


public class TestClass {

public static int size(List<String> names){
System.out.println("======line XYZ ");
return names.size()*2;
}
public static void process(List<String> names, Carnivore c){
c.eat(names);
}


public static void main(String[] args) {

List<String> fnames = Arrays.asList("a", "b", "c");

Tiger t = new Tiger();

process(fnames, t::eat);
process(fnames, t::calories);
process(fnames, TestClass::size ); // ----> this is where I am confused.
}
}

如您所见,静态方法 process(List<String> names, Carnivore c)采用对象类型 Carnivore .方法调用 process(fnames, TestClass::size )有效,并且没有编译时错误,这怎么可能?我无法理解此方法调用的内部工作原理。我期待一个错误,因为 TestClass不是 Carnivore .

我找到的最佳答案:“您可以显式传递 Carnivore 实例,也可以传递对与 Carnivore 抽象方法 eat(List<String> foods) 的参数列表相匹配的方法的引用”

部分pass a reference to a method that matches the parameter list of abstract method让我感到困惑。

感谢专家帮助我理解 process(fnames, TestClass::size ); 时会发生什么被称为。

最佳答案

Carnivore是具有单个抽象方法的功能接口(interface) int eat(List<String> foods); .

因此,任何符合 eat 签名的方法方法可用于实现接口(interface)。

public static int size(List<String> names)是这样一种方法,因为它需要一个 List<String>参数并返回 int .因此TestClass::size可以作为 Carnivore 类型的参数传递,这就是为什么 process(fnames, TestClass::size);通过编译。

顺便说一句,Tiger不必实现 Carnivore process(fnames, t::eat); 的接口(interface)通过编译,因为public int eat(List<String> foods)方法也匹配功能接口(interface)的单个​​抽象方法的签名。

关于java-8 - 将 "pass a reference"传递给与抽象方法的参数列表匹配的方法时,java 8 如何在内部求值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52962435/

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