Computer Science I / Abstract Data Use
Practice question · Put in order

Order what happens when an object is created and then used.

Hints
  1. Nothing can be assigned until there is somewhere to assign it.
  2. A method is entitled to assume the invariant only once something has established it.
Show the answer
  1. Memory is set aside to hold the new object's fields
  2. The constructor runs, with the arguments given at the point of creation
  3. The constructor rejects or corrects any argument that would break the invariant
  4. The object is handed back to the caller with its class invariant holding
  5. 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.

Read the lesson: Abstract Data Use →

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