Encapsulation

The concept of combining attributes and methods (data and functions), collectively referred to as members, into a single named object / entity.

 

Access / visibility of the members is controlled by access specifiers that define what is presented externally (public) and what is kept hidden (private).

 

Since an object should be responsible for its own data, only its public methods should be used to manipulate its data, and it is these public methods that are considered as its interface.

 

Only the barest minimum should be publicly visible and utilised externally.

 

Any invoking object should not care how the requested object’s methods are implemented, all they should care about is presenting the required information via a message to the object’s public interface in the correct format, so that it can receive an expected return or action.

 

Access to an object’s attributes should only be controlled by the object itself, and no other object should directly change an attribute of another object.

 

This concept is known as data hiding.

 

This is akin to the black box model. We don’t care what goes on inside as long as we get what we want from it, providing we supply the correct information to it.

 

So as long as the interface stays the same, the internal methods of the object can be changed or improved as/if required.

 

Reduces complexity and dependencies, so that a change in one place won’t require multiple changes elsewhere.

 

In this example, objectA is instantiated on line 26, we then access its public set method to give values to its private data members, and finally we access those private data members using the public get methods on line 30:

Hello, World!

 

 

Access to the object’s private data is completely controlled by the object itself. We cannot directly access (set or get) at its attributes without using its own methods.

Leave a Reply