OOP - Encapsulation

The process of bundling data and methods into one object (this is the AQA focus).

One of the main benefits of bundling the data and the methods together inside the object is that access to the data can be restricted, so that only the methods within the object can access or change the data.

Why do we need to restrict access to data?

  • To make programs robust

  • To allow developers to focus on their own work

  • To make programs easier to enhance.

To whom are we restricting access to data?

Other programmers

When working in a team of programmers you will know your part of the program well, but maybe not other elements. You will know the rules for how your data can be changed. Others may not. If you protect your data so it can only be changed in accordance with the rules you program, you prevent other programmers making illegal changes to that data.

Example: A bank account has an attribute called balance. The only way the value in this attribute should change is by crediting or debiting the account.

How do we restrict access?

Members are ‘flagged’ as either public or private (there is another flag we will visit later).

Private members can only be accessed inside an object.

Public members can be accessed from outside the object (and also internally).


Key Terms

Attribute

A named data value that describes the entity. It has a data type. It is a component of an object

Field

A protected attribute.

Property

An accessor to a field (get/set)

Method

A component of the object that does something.

Member

A component of the object that can be accessed

State

The value held in an attribute