Free Object-oriented basics lessonsObject-oriented basics · Stage 1 · Protecting state · Step 1
Encapsulation and invariants
Why fields are private, what an invariant is, and how access modifiers and careful getters keep an object valid. About 13 minutes.
Which design best protects an invariant that a Temperature is never below absolute zero?
- AA private field, set only in the constructor and in a method that validates the value
- BA public field with a comment saying not to go below absolute zero
- CA private field with a setter that accepts any double
Show the answer
A private field, set only in the constructor and in a method that validates the value. Every route to the field goes through a check.
4 questions on this idea
Short questions that apply the idea to new cases: trace it, work out a number, put steps in order. A wrong answer explains itself.
Answer them in your browserFree account, no card. Your progress is saved, and the idea comes back in a quick review later.
Sign up free to solve