This is part 2 in the series “A Beginner’s Guide to Object-Oriented Programming with Apex” and will cover the aspect of Encapsulation.
A Beginner’s Guide to Object-Oriented Programming with Apex
- Introduction
- Encapsulation (this post)
- Abstraction
- Polymorphism
What the hell is Encapsulation?
Encapsulation isn’t a tricky concept in itself but some confusion does arise from it’s close relationship with Abstraction (to be covered in my next post). Broadly it is defined as one of, or both of the following:
- An information hiding mechanism.
- A bundling of data and methods that operate on that data.
These are pretty abstract statements but in reality are very simple. I will demystify them with examples below but for now let’s use an analogy:
Imagine you have a watch (or if you have one just consider it, don’t worry about the imagining part) that tells you the date and time. You can adjust the date and time using buttons/knobs/switches but you have no idea what happens inside the watch, just that it results in the date and time changing. You have some data (the date and time), you have some methods to operate on that data (buttons/knobs/switches) and there is a whole lot of stuff going on in the background that you don’t know about (and it’s better that way, imagine you had to adjust all those bits and pieces yourself).
That’s encapsulation baby!