1Z0-803 · Question #223
Given: public class ComputeSum { public int x; public int y; public int sum; public ComputeSum (int nx, int ny) { x = nx; y =ny; updateSum(); } public void setX(int nx) { x = nx; updateSum();} public
The correct answer is A. The x field B. The y field C. The sum field. To maintain the invariant that sum is always x + y, the fields x, y, and sum must be protected from direct external modification. Making these fields private ensures that any changes to x or y must occur through controlled methods that also update sum.
Question
Given:
public class ComputeSum { public int x; public int y; public int sum; public ComputeSum (int nx, int ny) { x = nx; y =ny; updateSum(); } public void setX(int nx) { x = nx; updateSum();} public void setY(int ny) { x = ny; updateSum();} void updateSum() { sum = x + y;} } This class needs to protect an invariant on the sum field. Which three members must have the private access modifier to ensure that this invariant is maintained?
Options
- AThe x field
- BThe y field
- CThe sum field
- DThe ComputerSum ( ) constructor
- EThe setX ( ) method
- FThe setY ( ) method
How the community answered
(46 responses)- A74% (34)
- D4% (2)
- E15% (7)
- F7% (3)
Why each option
To maintain the invariant that `sum` is always `x + y`, the fields `x`, `y`, and `sum` must be protected from direct external modification. Making these fields private ensures that any changes to `x` or `y` must occur through controlled methods that also update `sum`.
Making the `x` field private prevents external classes from directly modifying its value, ensuring that any changes go through the `setX()` method which correctly calls `updateSum()` to maintain the invariant.
Making the `y` field private prevents external classes from directly modifying its value, ensuring that any changes go through the `setY()` method which correctly calls `updateSum()` to maintain the invariant.
Making the `sum` field private prevents external classes from directly modifying its value, ensuring that `sum` can only be updated internally by the `updateSum()` method, thereby maintaining the `x + y` invariant.
Making the constructor private would prevent the creation of `ComputeSum` objects, which is not the mechanism for protecting the internal `sum` invariant after object creation.
Making `setX()` private would prevent controlled modification of `x` from outside the class, forcing `x` to be immutable or requiring direct field exposure, which undermines the invariant protection.
Making `setY()` private would prevent controlled modification of `y` from outside the class, forcing `y` to be immutable or requiring direct field exposure, which undermines the invariant protection.
Concept tested: Data encapsulation and invariant protection in Java
Source: https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
Topics
Community Discussion
No community discussion yet for this question.