For which field type is a defensive copy unnecessary?
Immutable objects such as String, Integer and LocalDate can be shared safely.
Encapsulation · Exercise 1 of 4
Twenty multiple-choice questions on encapsulation in Java: data hiding, getters and setters, validation, invariants, defensive copies, read-only properties and immutability. Pick an option to check your answer instantly.
For which field type is a defensive copy unnecessary?
Immutable objects such as String, Integer and LocalDate can be shared safely.
What is a class invariant?
Example: balance ≥ 0, or min ≤ max.
Why is generating a public setter for every private field poor encapsulation?
Add setters only where change is a valid operation.
Which code follows "tell, don't ask"?
The account applies its own rules.
Why is a public setStatus(String) method on an Order risky?
Expose actions like pay() and ship() instead.
A class stores price as double and later switches to paise in a long. With proper encapsulation, what changes for callers?
Hiding the representation is what makes this change safe.
Which is a good example of a write-only property?
Offer setPassword and checkPassword, not getPassword.
Why might a constructor call the class's own (final or private) validating setters?
Keep such setters final so subclasses cannot change them during construction.
Do simple getters and setters make Java programs noticeably slower?
Encapsulation costs essentially nothing at run time.
What does record Point(int x, int y) {} generate?
Records are encapsulated, immutable data carriers.
Timed online tests with instant scores and explanations.