Given the following definitions:
interface InterfaceOne<T> { void foo();/*from www . j a v a 2s . c om*/ } interface InterfaceTwo<T> { T foo(); } interface InterfaceThree<T> { void foo(T arg); } interface InterfaceFour<T> { T foo(T arg); } public class Main { public static void main(String []args) { // STATEMENT System.out.println(val.foo()); } }
Which one of the following statements can be replaced with the line marked with the comment STATEMENT that the program will print the result that is same as the call LocalDateTime.now()
?
a) InterfaceOne<LocalDateTime> val = LocalDateTime::now; b) InterfaceTwo<LocalDateTime> val = LocalDateTime::now; c) InterfaceThree<LocalDateTime> val = LocalDateTime::now; d) InterfaceFour<LocalDateTime> val = LocalDateTime::now;
b)
the method now()
in LocalDateTime is declared with the signature:
LocalDateTime now()
the matching functional interface should also have an abstract method that takes no argument and returns a value of type T.
Since InterfaceTwo
has the abstract method declared as T foo()
,
the statement
InterfaceTwo<LocalDateTime> val = LocalDateTime::now;
succeeds.
From the interface, the method can be invoked with val.foo()
; since val refers to LocalDateTime::now, and it is equivalent to making the call LocalDateTime.now()
.