Understanding Encapsulation in Object-Oriented Programming: A Practical Example

 



Pillars in Object oriented programming:

There are four Pillars of OOPs 

1) Encapsulation: Encapsulation is the bundling of data and methods into a single unit called a class. It allows for the hiding of internal details and provides a way to control access to the data. Encapsulation promotes the principle of data hiding and information hiding.

2) Inheritance: Inheritance is a mechanism that allows a class (subclass) to inherit properties and behaviors from another class (superclass). It enables code reuse and promotes the concept of hierarchical relationships between classes. The subclass can add or modify existing behavior without changing the original superclass.

3) Abstraction: Abstraction focuses on representing the essential features of an object while hiding unnecessary details. It allows you to create abstract classes or interfaces that define a common structure and behavior for a group of related objects. Abstraction helps in managing complexity and building modular programs.

4) Polymorphism: Polymorphism means "many forms." It refers to the ability of an object to take on multiple forms and exhibit different behaviors depending on the context. Polymorphism allows objects of different classes to be treated as objects of a common superclass. It enables code flexibility, extensibility, and method overriding.

These four pillars form the foundation of object-oriented programming and help in creating modular, maintainable, and reusable code.

All pillars of oops are most important when it comes to use of OOPs. We will check one by one.


1) Encapsulation:

 We see in last blog what is Encapsulation in one line. That is Binding of data. Now the question is how? And why?

But before going to check on these questions lets discuss what is encapsulation in details.

Encapsulation is nothing but protecting data, properties and functions of an object from another object.




So how to hide data in other words methods from users. Python community suggested to use “_” (underscore) before the method which you want to hide from the users. For example: if you want to hide name of an person you can use following code

Class Person:

def __init__(self,name):

Self._name = name

 

x= Person()

Now as per method when we call “x.name” it wont give you the name of the person.

But its not like you can not hide every object, you can access the method but need to use below syntax "Variable.class.method" so that it will give the required result in above case to get name 

print(x.Person._name())

It will print the name of the person.


Implementation of Encapsulation:

To implement the Encapsulation we use getter and setter methods

Previous example we have see in OOPs introduction part

OOPs introduction



For details please check OOPs introduction Blog  OOPs introduction