1Z0-809 practice question 9 of 25

Given: public interface Moveable { public default void walk (Integer distance) {System.out.println(“Walking”);) public void run(Integer distance); } Which statement is true?

Full set: 196 questions
Answer options
A: Moveable can be used as below:Moveable animal = n - > System.out.println(“Running” + n);animal.run(100);animal.walk(20); Correct answer
B: Moveable can be used as below:Moveable animal = n - > n + 10;animal.run(100);animal.walk(20);
C: Moveable can be used as below:Moveable animal = (Integer n) - > System.out.println(n);animal.run(100);Moveable.walk(20);
D: Movable cannot be used in a lambda expression.
Correct Answer:
A. Moveable can be used as below:Moveable animal = n - > System.out.println(“Running” + n);animal.run(100);animal.walk(20);
Explanation

The Moveable interface is a functional interface because it declares exactly one abstract method, run. Therefore, it can be a target for a lambda expression. Option A correctly provides a lambda expression n -> System.out.println("Running" + n) for the run method. The code then correctly calls the implemented run method and the inherited default walk method on the instance animal. The use of a raw type Moveable is valid, though it may generate a compiler warning.

Why Incorrect

B: The lambda n -> n + 10 has a return value, which is incompatible with the run method's void return type, causing a compilation error. C: The call Moveable.walk(20) is invalid. walk is a default (instance) method, not a static method, and must be invoked on an object instance (e.g., animal.walk(20)). D: This is incorrect. An interface with a single abstract method is a functional interface and can be implemented using a lambda expression.

References

- The Java™ Language Specification, Java SE 8 Edition, Section 9.8, "Functional Interfaces". It states, "A functional interface is an interface that has just one abstract method (aside from the methods of Object)".

- The Java™ Tutorials, "Lambda Expressions". Oracle Corporation. This tutorial explains that a lambda expression can be used to represent an instance of a functional interface.

- The Java™ Language Specification, Java SE 8 Edition, Section 9.4.1, "Default Methods". It clarifies that default methods are instance methods.

Scroll to Top