Object Oriented Programming Encapsulation

This is the third part of the OOP primer series, where we discuss the concept of Encapsulation and why its necesscary for objects to have their data contained within the object itself.

As always, if there are any comments please feel free to email me.

Encapsulation

If I came up to you and asked for your social security number, would you give it to me? I would hope not because that is your private information, and only those who have certain permissions should be able to access that information such as your spouse, the IRS, or the Government. It is not my business to know your social security number and you shouldn’t give it to me because I am neither a Federal Agent, an IRS Agent, or your spouse, I am just the author of this paper. Objects take this same approach when it comes to their data through the idea of encapsulation. Encapsulation is where the Objects data members and methods are enclosed within the objects themselves. Going back to you, you won’t give me your social security number because that is protected information, only certain people can have access to. What if I ask you “What’s the most embarrassing moment in your life?”, maybe you don’t want to share that information with anyone, especially the IRS, because that information is private, to you and only you. Though if I ask for your name, you would probably give me your name because that information is public, most people have a name that they would like to be called by or addressed as and that information is most likely public information either through a phonebook, social media, or that one embarrassing Facebook post your parents tagged you in.

Objects behave in the same way, their data members have certain restrictions to who they can be exposed to, and what can they be exposed by. If we go back to the example of you, you have a social security number that is data that is only accessible by a few special other person objects, you have a name that is accessible by all person objects, but you have an embarrassing secret that is only accessible to you and only you.

Written on March 4, 2023