Why this doesn't work? I get compiler error "Cannot make static reference to the non static method print..."
public class Chapter3 {
public void print(String s) {
System.out.println(s);
}
public static void main(String[] args) {
Arrays.asList("a", "b", "c").forEach(Chapter3::print);
}
}
Regardless of whether you use method references, lambda expressions or ordinary method calls, an instance method requires an appropriate instance for the invocation. The instance may be supplied by the function invocation, e.g. if forEach
expected a BiConsumer<Chapter3,String>
it worked. But since forEach
expects a Consumer<String>
in your case, there is no instance of Chapter3
in scope. You can fix this easily by either, changing Chapter3.print
to a static
method or by providing an instance as target for the method invocation:
public class Chapter3 {
public void print(String s) {
System.out.println(s);
}
public static void main(String[] args) {
Arrays.asList("a", "b", "c").forEach(new Chapter3()::print);
}
}
Here, the result of new Chapter3()
, a new instance of Chapter3
, will be captured for the method reference to its print
method and a Consumer<String>
invoking the method on that instance can be constructed.