LearnFrenzy
Sign in Take a free test

Encapsulation · Find the Error · Question 2

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

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

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

Main.java
class Aadhaar {
    private final String number;
    Aadhaar(String n) { number = n; }
    public String getNumber() { return number; }
    public void setNumber(String n) { number = n; }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(new Aadhaar("1234").getNumber());
    }
}
  • A number must be public
  • B number is final, so it can only be assigned in the constructor; a read-only property must not have a setter Correct
  • C Getters cannot return final fields
  • D Strings cannot be final
Correct Answer: Option B

Remove setNumber.

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