What is encapsulation in programming?
Encapsulation in programming is like packing your lunch in a lunchbox. Just like you put your sandwich, apple, and juice in a lunchbox to…
Encapsulation in programming is like packing your lunch in a lunchbox. Just like you put your sandwich, apple, and juice in a lunchbox to keep them together and safe, encapsulation bundles data and methods that work on the data within one unit, like a class in programming. Let’s make it fun and easy to understand with a real-life example and, of course, some smiles 😊!
Imagine you’re preparing a lunchbox for a picnic 🍱🌳. You put in a sandwich 🥪, an apple 🍎, and a juice box 🧃. The lunchbox keeps everything neatly packed and protects the food. Other people at the picnic don’t need to know exactly what’s in your lunchbox or how you made your sandwich; they just see a lunchbox.
In programming, this is like having a class with private variables (your sandwich, apple, and juice) and public methods (ways to interact with your lunchbox). Here’s a simple example in Python:
class Lunchbox:
def __init__(self):
self.__sandwich = "Peanut Butter & Jelly" # Private variable
self.__apple = "Granny Smith" # Private variable
self.__juice = "Apple Juice" # Private variable
def whats_in_my_lunchbox(self):
return f"Sandwich: {self.__sandwich}, Apple: {self.__apple}, Juice: {self.__juice}"
# Creating a Lunchbox object
my_lunchbox = Lunchbox()
# Asking what's in the lunchbox
print(my_lunchbox.whats_in_my_lunchbox()) # Outputs: Sandwich: Peanut Butter & Jelly, Apple: Granny Smith, Juice: Apple JuiceIn this code:
The Lunchbox class encapsulates (packs) the details about the lunch (sandwich, apple, and juice).
The variables are private (__sandwich, __apple, __juice), which means they can’t be accessed directly from outside the class, just like others can’t see what’s in your lunchbox without opening it.
The method whats_in_my_lunchbox is public, allowing you to tell others what’s inside your lunchbox without them needing to open it.
Encapsulation helps keep the data inside a class safe from outside interference and to interact with the outside world in a controlled way, just like how you can tell people what’s in your lunchbox without them needing to open it. This keeps your data safe and organized, just like your neatly packed lunchbox at the picnic! 😊🍱🥪🍎🧃
If you found them helpful:
Show some love with a 50-clap
Drop a comment.
Share your favorite part!
Discover more in my online courses at Appmillers
Follow on LinkedIn: Elshad Karimov
Follow on X (Twitter) : Elshad Karimov


