Oracle Certified Professional Java Se 11 Developer · Free Practice Question Hard

Question 102

Question ID: UKOCP38454


Given code:


Which of the following interface definitions can replace /*INSERT*/ such that there is no compilation error?

Choose 4 options.

  • A
  • B
  • C
  • D
  • E
  • F
  • G
Reveal correct answers

Correct answers: A, B, C, F

Explanation

UKOCP38454:

Target type of lambda expression must be a Functional interface.

Functional interface must have only one non-overriding abstract method but Functional interface can have constant variables, static methods, default methods, private methods and overriding abstract methods [equals(Object) method, toString() method etc. from Object class].


Let's check which of the given options are Functional interfaces:

✓  MyInterface has only one non-overriding abstract method [toStr()] and hence a Functional interface.

Given lambda expression () -> "" means method accepts no argument and returns a String object. It is a correct implementation of toStr() method.


✓  MyInterface has only one non-overriding abstract method [toStr()] and toString() method is overriding abstract method, therefore it is also a valid Functional interface.

() -> ""; is the correct implementation of toStr() method.


✓  MyInterface has only one non-overriding abstract method [toStr()] and toString() method is overriding abstract method & print(String) is the static method, therefore it is also a valid Functional interface.

() -> ""; is the correct implementation of toStr() method.


✗  My interface has two non-overriding abstract methods. Please note that boolean equals(Object); is overriding abstract method but boolean equals(MyInterface); is non-overriding abstract method.


✗  String toString(); is overriding abstract method and hence in this case, MyInterface doesn't contain non-overriding abstract method. Therefore it is not a Functional interface.


✓  MyInterface has only one non-overriding abstract method [test()] and hence a Functional interface.

As String class implements CharSequence, therefore value returned by Lambda expression [""] (String type) can easily be assigned to CharSequence reference.

() -> ""; is the correct implementation of CharSequence test();


✗  MyInterface has only one non-overriding abstract method [m()] and hence a Functional interface.

Value returned by Lambda expression [""] (String type) can not be assigned to StringBuilder reference.

() -> ""; is NOT the correct implementation of StringBuilder m();

Discussion

Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.

You must be logged in to post a comment.

Preparing For

Your Certification?

255+ certifications
Detailed explanations
Free PDF samples

Has All The Questions You Need