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.
Just in case if you are trying to apply an instance method from the same object where your code runs
Arrays.asList("a", "b", "c").forEach(this::print);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With