我一直在使用 java 8 功能接口,当我开始执行下面的代码时,我注意到一些不寻常的东西。
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
is not 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 );
被调用时会发生什么,我们将不胜感激。