Given these class definitions:
class Book { public void read() { System.out.println("read!"); }/* ww w. j av a 2 s .c o m*/ } public class Main { // DEFINE READBOOK HERE public static void main(String []args) { new Main().readBook(Book::new); } }
Which one of the following code segments when replaced with the comment "DEFINE READBOOK
HERE" inside the Main class will result in printing "read!" on the console?.
a) private void readBook(Supplier<? extends Book> book) { book.get().read();/* www. j av a 2 s . c o m*/ } b) private static void readBook(Supplier<? extends Book> book) { Book::read; } c) private void readBook(Consumer<? extends Book> book) { book.accept(); } d) private void readBook(Function<? extends Book> book) { book.apply(Book::read); }
a)
the Supplier<T> interface declares the abstract method get()
.
the get()
method does not take any arguments and returns an object of type T.
hence, the call book.get()
.read()
succeeds and prints "read!" on the console.
option b) Method references can be used in places where lambda expressions can be used. hence, this code segment will result in a compiler error.
option c) the accept()
method in the Consumer<T> interface requires an argument to be passed - since it is missing here, it will result in a compiler error.
option d) the Function<T, R> interface takes two type parameters and hence this method definition will result in a compiler error.