LearnFrenzy
Sign in Take a free test

Static and Final Keywords · Find the Error · Question 8

Error: a setter assigning a final field Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

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

Main.java
class User {
    private final String email;
    User(String email) { this.email = email; }
    void setEmail(String email) { this.email = email; }
}

public class Main {
    public static void main(String[] args) {
        new User("a@b.com").setEmail("c@d.com");
    }
}
  • A email must be public
  • B email is final, so it can be assigned only in the constructor – a setter cannot change it Correct
  • C setEmail must be static
  • D The constructor must call setEmail
Correct Answer: Option B

For an immutable class, return a new User instead of a setter.

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