Student::debug is not an invocation of the method. It is a method reference. It is simply a shortcut for the programmer. The compiler converts it into an actual method call, something like this:
Hi,
At question 35 you say the lists forEach method requires a method with a parameter.
Nevertheless the method debug() does not take any parameter, why does this work, and example 35 dont?
Thanks.
Please read the post above. It explains exactly what you are asking about debug().
I am not sure which question 35 are you referring to. Please mention the questionid so that the question can be identified definitively.
If you like our products and services, please help us by posting your review here.
The forEach method expects a Consumer object (i.e. an object of a class that implements Consumer). Since, Consumer is a functional interface (i.e. it has exactly one abstract method, which takes Student as an argument, in this case), the compiler provides help in creating such as class if you tell which method you want to invoke when Consumer's functional method is invoked. Method reference such as s::debug() works because the compiler knows that it need to invoke the debug method on the student instance passed to the functional method (see code above).
In case of n.getList().forEach(Names::printNames); (of question enthuware.ocpjp.ii.v11.2.1789), the compiler is not able to figure out how to call the printNames method. Since printNames is not static, the compiler can't use Names.printNames() to invoke it on Names class, and since the list is of Strings (not Names), the compiler has a reference to a String, it doesn't have any reference to an instance of Names on which to invoke printNames() method. Thus there is no way for the compiler to create an appropriate implementation of the Consumer interface using Name::printNames method reference.
I will suggest you to go through a good book because it is not really possible to provide complete details on forum posts.
HTH,
Paul.
If you like our products and services, please help us by posting your review here.