LearnFrenzy
Sign in Take a free test

Classes and Objects · Find the Error · Question 9

Error: an anonymous class using a changing local variable Answer, explanation & discussion

  • Find the error
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

Main.java
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links