LearnFrenzy
Sign in Take a free test

Encapsulation · Find the Error · Question 1

Error: bypassing a setter to write a private field Answer, explanation & discussion

  • Find the error
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

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

Main.java
class Battery {
    private int charge = 50;
    public void setCharge(int c) { if (c >= 0 && c <= 100) charge = c; }
    public int getCharge() { return charge; }
}

public class Main {
    public static void main(String[] args) {
        Battery b = new Battery();
        b.charge = 150;
        System.out.println(b.getCharge());
    }
}
  • A charge must be static
  • B charge is private, so Main cannot assign it directly; it must use setCharge, which would reject 150 Correct
  • C getCharge must be private
  • D 150 is not an int
Correct Answer: Option B

The compiler enforces encapsulation.

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