Encapsulation
As previously stated, encapsulation is a key concept in OOP. The principle here is that you protect the data in your class and ensure that the data can only be manipulated (retrieved and/or changed) via your code. In other words, you have control over how external classes interact with your internal state (data). So, how do we do this?
Achieving encapsulation
Basic encapsulation is very easy to achieve. You simply mark your data as private
and manipulate the data via public
methods. Thus, external classes cannot access the data directly (as it is private
); these external classes must go through your public
methods to retrieve or change the data.
These public
methods make up the class’s "interface"; in other words, how you interact with the class. This “interface” (group of public
methods) is very different from and not to be confused with the interface
language construct (Chapter 10). Figure 8.16 presents a code example to help...