In our current society, we are more than used to live with technology gadgets, most of them not even in the minds of our ancestors. Things as common and “simple” as a remote for our TV, just to mention one, that avoid the need to stand up for interacting with our tv set, but… do you know how remote controls work? What is the principle that allows them to send an instruction to the tv set?
Is it crucial to understand that in order to make good use of the remote? The truth is… while writing this very article I don’t yet know how it works (I’m curious, though), but despite that, I’ve been successfully using remotes since I have a memory. So, I can conclude that it’s not relevant to know how it works internally to use it correctly.
That is what is called abstraction: Hiding lower-level details, exposing only those relevant for the use of some device or system, and this principle applies also to software systems.
In the Object-Oriented Paradigm, we make use of abstraction when we hide details regarding the data of our objects, exposing to the “outside” environment only what’s needed for interacting with it, this technique is called Encapsulation.
For implementing the Encapsulation principle we need a mechanism to control the access and visibility of the methods and properties of an object, in OOP this is achieved through the use of access modifiers. Most of the OOP programming languages share the support for at least this 3 access modifiers:
- public: Properties/methods are visible and accessible from any other class
- private: Properties/methods are accessible only from within the owner class
- protected: As with the private modifier, properties/methods are accessible only from within the owner class, but when using protected they’re also accessible from a subclass of it
Still, the level of encapsulation they enforce can change for each programming language, and some can even add some other access modifiers.
In Java, for example, it exists a fourth access modifier, called “default”. This provides direct access to a property of a class only from classes within the same package, regardless if they’re subclasses of it or not. The default access modifier is set automatically when we don’t define any access modifier to a property/method.
In encapsulation, the properties of a class will be hidden and only accessed through methods of their owner class. For achieving this, we declare the variables of a class as private and provide public setter and getter methods to provide access to the properties.
Encapsulation is a core concept in the OOP paradigm that allows us to control the level of access for a class member and hide details of their implementation