1Z0-819 · Question #165
import java.util.function.BiFunction; public class Pair<T, Boolean> { final BiFunction<T, Boolean, T> validator; T left = null; T right = null; private Pair() { validator = null; }…
The correct answer is B. left and right must be private. Making left and right private is the critical minimum because it removes all direct field assignment from outside the class - without it, any code in the same package can write p.left = badValue, instantly violating the invariant regardless of what the validator says. Once…
Question
Options
- AsetLeft and setRight must be protected.
- Bleft and right must be private.
- CisValid must be public.
- Dleft, right, setLeft, and setRight must be private.
How the community answered
(37 responses)- A3% (1)
- B76% (28)
- C8% (3)
- D14% (5)
Explanation
Making left and right private is the critical minimum because it removes all direct field assignment from outside the class - without it, any code in the same package can write p.left = badValue, instantly violating the invariant regardless of what the validator says. Once those fields are private, external code must go through the class's own methods to modify state, and setX - the only validated entry point - is the natural channel for that.
Why A is wrong: Making setLeft/setRight protected would actually widen their access to subclasses in any package, making the invariant harder to enforce, not easier. Protection isn't the same as restriction.
Why C is wrong: The visibility of isValid has no effect on whether the invariant holds - it only determines who can ask whether it holds. Querying state does not protect state.
Why D is wrong: D is a sufficient solution, but not the smallest one - it makes four things private (left, right, setLeft, setRight) when the two field changes in B address the root vulnerability: unguarded direct field access. The setters being package-private is an internal implementation concern, not an external encapsulation gap.
Memory tip: Think "protect the data, not the doors." Private fields seal the vault; access modifiers on methods just control which hallways lead to it. The invariant breaks when someone walks straight through the wall (direct field access), not when they use a side door (a setter).
Topics
Community Discussion
No community discussion yet for this question.