Question 1
Back to Exercise
The program below does not compile. Which statement correctly describes the problem?
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!