Question 9
Back to Exercise
The program below does not compile. Which statement correctly describes the problem?
public class Main {
interface Action { void run(); }
public static void main(String[] args) {
int count = 0;
Action a = new Action() {
@Override
public void run() { System.out.println("count is " + count); }
};
count++;
a.run();
}
}
- A Action must be public
- B count is changed after the class captures it, so it is not effectively final; local and anonymous classes (and lambdas) may only capture effectively final variables Correct
- C run must return int
- D Interfaces cannot be nested
Correct Answer: Option B
Copy it into a final variable, or keep the counter in a field or an object.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!