到目前为止,我已经成功找到了所有我所需要的答案,但这一个让我感到困惑。假设我们有以下示例代码:
public class Animal {
private String species;
private boolean canHop;
private boolean canSwim;
public Animal(String speciesName, boolean hopper, boolean swimmer) {
species = speciesName;
canHop = hopper;
canSwim = swimmer;
}
public boolean canHop() { return canHop; }
public boolean canSwim() { return canSwim; }
public String toString() { return species; }
}
public interface CheckAnimal {
public boolean test(Animal a);
}
public class FindSameAnimals {
private static void print(Animal animal, CheckAnimal trait) {
if(trait.test(animal)){
System.out.println(animal);
}
public static void main(String[] args) {
print(new Animal("fish", false, true), a -> a.canHop());
}
}
《OCA考试指南(考试1Z0-808)》的书中说这两行代码是等价的:
a -> a.canHop()
(Animal a) -> { return a.canHop(); }
这是否意味着,在幕后,Java会在第一种情况下将关键字return添加到代码中?
如果答案是YES,则下一个代码如何编译(假设其他所有内容都正确):
static int counter = 0;
ExecutorService service = Executors.newSingleThreadExecutor();
service.execute(() -> counter++));
如果我们知道execute和Runnable的run的签名是:
void execute(Runnable command)
void run()
如果答案是否定的,那么Java如何知道什么时候需要返回值,什么时候不需要呢?也许在
a -> a.canHop()
如果我们希望忽略方法的 布尔 返回类型。