1

Below code is compiling successfully where I am assigning bound method reference to functional interface.

Consumer<String> con = System.out::println;

But below code where I am assigning unbound method reference to functional interface is giving error.

Consumer<String> con = PrintStream::println;

Error message is

"Cannot make a static reference to the non-static method println(String) from the type PrintStream"

Help me to understand what is wrong here.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724

1 Answers1

2

The method reference operator being:

System.out::println;

Can only by applied to:

  • A reference of a static method ContainingClass::staticMethodName

  • An instance method of a particular object containingObject::instanceMethodName

  • An instance method of an arbitrary object of a particular type ContainingType::methodName

  • A constructor ClassName::new

For more information visit Java Method References

In the above case the PrintStream class has a declaration for the println method as a non-static method therefore requires an instance in order to be specified using a method reference operator, for example:

PrintStream ps = new PrintStream("filename");
Consumer<String> con = ps::println;
  • That is why It is clearly listed how this operator can be utilised with an instance as well. Rather than just jumping directly to the solution an explanation has been specified elaborating how this could be used on an instance directly and used upon a class only if it is therefore static. – Justin Joseph Mar 18 '21 at 19:40
  • The above points I listed about the method reference operator was taken from: https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html My intention was to list the points regarding this operator, thank you I have modified the above for clarity. – Justin Joseph Mar 19 '21 at 11:33
  • Yes I have specified the link. – Justin Joseph Mar 19 '21 at 12:22