CSE Roadmap

Core tier · about 2 hours · 7 parts

Part 3 of 7 · 1 min read

State, behaviour and identity

Three things every object has.

An object has three parts (common practice in object-oriented teaching):

  • State: the data it holds now. A Room holds an id and a capacity.
  • Behaviour: what it can do. A Room can say whether a group fits.
  • Identity: what makes it this object and not another, even when the data is equal.

Two rooms can both have capacity 4. They are still two rooms. If one is closed for repair, the other is not. Identity is what lets a program talk about "that room" over time.

A constructor is the special method that builds an object and sets its first state. In the Room class above, the constructor stores the id and the capacity. The keyword this refers to the object being built or used, which separates the field this.id from the parameter id.

A field declared static belongs to the class, not to any one object. One shared counter for all rooms would be static. Use it sparingly: shared state is hard to test, as Level 0 module 5 noted.

Check yourself: 1. Which of the three parts distinguishes two rooms that have equal data? 2. What does this mean inside a constructor? 3. Why is shared static data risky?