Chapter 2. Encapsulation

Table of Contents

What is encapsulation?

Important

Encapsulation

is the grouping of related ideas into one unit, which can thereafter be referred to by a single name.

Came from the early 40's: The same pattern of instructions appear multiple times, why not give them a single name and re-use them?

Subroutine was born. Saves computer memory. Then people realized: Saves human memory too!

Encapsulation in OO has a similar purpose, but is more sophisticated.

Important

Object-Oriented encapsulation

is the packaging of operations and attributes representing a state into an object type so that it is accessible or modifiable only via the interface provided by the encapsulation

Example: Hominoid class, has operations such as:

turnLeft

with turns hominoid to the left by 90 degrees

advance

moves hominoid one step forward

Each operation is a procedure or function that is normally visible to other objects, which means it can be called upon by other objects.

Attributes represent information that an object remembers. Attributes are only accessed via object's operations. In other words, no other object can acces an attribute directly by grabbing the underlaying variables. Another object has to go though the object's operations.

Figure 2.1. Operations and attributes of Hominoid
Operations and attributes of Hominoid

Only the operations may acces attibutes, they form a protective ring around the core variables implemented in the object.

Example: location operation is used to access the loc variable.

Important

variable(s)

One or more variables implement one or more attributes.

Examples:

  • a cpuSpeed attribute can be implemented with one variable cpuSpeed

  • a location attribute can be implemented with two variables: locationX, locationY

  • the attributes location and facingWall are both implemented with one location variable

an object structure resembles a medieval city, with a protective wall. It can be accessed only through well-defined and well-guarded gates.

Figure 2.2. The Hominoid's City
The Hominoid's City

Staunch, hones yeopersons would enter the city via the gates. They would buy their pigs in the marketplace and then leave through a gate. Only the most villainous villeins and scrofulous scalawags would scale the wall, swipe a swine, and steal away over the parapets.

Book: Chapter 1.1