![]() |
VOOZH | about |
Encapsulation is the practice of bundling data (attributes) and the methods that manipulate the data into a single unit (class). It also hides the internal state of an object from external interference and unauthorized access. Only specific methods are allowed to interact with the object's state, ensuring better control, security and integrity of data.
Encapsulation helps to reduce the complexity of the system by limiting how the internal data of an object can be accessed or modified. It is a key concept in OOP that ensures objects are self-contained and interact with each other through well-defined interfaces.
👁 EncapsulationFor example, think of a restaurant where a customer orders food through a waiter. The customer cannot directly interact with the chef, just as objects cannot directly modify each other’s internal states in an encapsulated system. Instead, methods are defined to handle the interactions, ensuring data security and integrity.
Note: An object is a collection of operations that shares a state. The collection of operations define the behavior of an object.
We will try to understand encapsulation using some examples in R programming language.
We are creating a list A with three fields: name, state and sector. We then assign a class name info to this list, effectively turning it into an object of the info class. The A object now encapsulates these properties. This allows us to group related data under a single object and its internal structure is protected from direct modification. When we print A, it shows the details of the object, including its class name and fields.
Output:
In this example, we are creating another list s with fields country, state and street_no. We assign the class address to this list, turning it into an object of the address class. Just like the previous example, this object encapsulates the properties related to an address. By encapsulating the address details within this object, we ensure that these details are bundled together and any updates are managed through defined methods.
Output:
In R, although it doesn't have formal encapsulation mechanisms like some other languages (e.g., private or protected fields), the principle can still be applied effectively by controlling how data is accessed and manipulated. For example, we can define functions that operate on the internal state of an object, ensuring that no external code can directly modify its properties.