I am trying to understand the concept of Method references. When trying out different calls, I stumbled upon a scenario which I cant fully understand.
When canClim is used without a parameter, it can be passed to forEach without problems although forEach takes a Consumer which should take in a parameter? When adding a parameter to canClim it prevents compiling?
However when canClim is declared as static it won't compile without adding static void canClim(Animal a) to the signature.
Shouldn't it be possible to call the static method without having a instance of the Animal class because it is static ?
Thanks!
import java.util.*;
class Animal {
void canClim() {
System.out.println("I am a climber!");
}
}
public class MethodReferencer {
public static void main(String[] args) {
Animal a = new Animal();
Animal b = new Animal();
List<Animal> list = new ArrayList<>(Arrays.asList(a, b));
list.forEach(Animal::canClim);
}
}
Animal.canClim()as a function which takes an Animal (this) as argument:canClim(Animal this). When you think of it that way, it becomes obvious that this is a valid Consumer<Animal>. Static methods, on the other hand, have nothis.thisis supplied to the accept of the consumer?