Practice question · Put in order
Order what happens when an object is created and then used.
- Memory is set aside to hold the new object's fields
- A public method is called, and may assume the invariant holds on entry
- The object is handed back to the caller with its class invariant holding
- The constructor runs, with the arguments given at the point of creation
- The constructor rejects or corrects any argument that would break the invariant
Hints
- Nothing can be assigned until there is somewhere to assign it.
- A method is entitled to assume the invariant only once something has established it.
Show the answer
- Memory is set aside to hold the new object's fields
- The constructor runs, with the arguments given at the point of creation
- The constructor rejects or corrects any argument that would break the invariant
- The object is handed back to the caller with its class invariant holding
- A public method is called, and may assume the invariant holds on entry
Why
Allocation comes first because the constructor needs fields to write into. The constructor then validates before the object escapes: that ordering is the whole point, since an object handed back in a broken state can never be repaired by the methods, which were written assuming the invariant already holds. Letting the object reach the caller before validation is the error, by then any method may already have been called on it.
Practise Abstract Data Use
The app has 6 more questions on this lesson, and keeps your place in the course. Computer Science I is free to start.
More questions on Abstract Data Use
- A stack ADT implemented with a fixed-size array can overflow when pushed too many times; the same ADT over a…
- A team replaces a stack's array implementation with a linked-node one. The published operations behave…
- A library documents a function's behaviour but not its complexity. Callers then write loops assuming it is…
- Because an ADT's interface says nothing about cost, two correct implementations of the same interface can…
- A stack ADT is being documented. Sort each statement by whether it belongs in the published interface or is…