Chapter 4. State retention

A class is a general description: Every Hominoid has a position.

An object is an "instance" of a class and has specific values for the attributes: This Hominoid is at position 2x5

Objects keep their state (in attributes).

Traditional methods need to have parameters. They don't know about their previous existence.

But objects are aware of the past. they retain information inside -> objects don't die, they are ready to execute again

Example from Monopoly: A property knows its value. So when buying or selling a property, there is no need for the parameter "price".

Example from Hominoid. A Hominoid is at position 2x5, facing up. After the operation "forward" it is not at 2x4, facing up. Another invocation of forward will move it to 2x3 (so the results are different).

Techspeak: an object retains state. state is the set of values that an object holds. example: hominoid retains knwoledgde about the square and the location.

State can be compared to global variables, but here they are are encapsulated with their functions.

Encapsulation, information hiding and state are the core of object orientation. However, these concepts are not new, they used to be called ADT (abstract data type).

Practice: Assume a Hominoid with the following state:

  • Direction : (N,E,S,W) = N

  • PosX : int = 5

  • PosY : int = 5

Where the location (1,1) is the top left (most north, most west) and location (20,20) is the bottom right (most south, most east), X goes east - west and Y goes north - south.

The operation advance() moves the hominoid one step forward, the operations turnLeft() and turnRight() turn the hominoid by 90 degress.

Assume the following function calls:

  1. advance()

  2. turnRight()

  3. advance()

  4. advance()

  5. turnRight()

  6. advance()

  7. turnLeft()

  8. turnLeft()

  9. advance()

What is the Hominoids state after this code?