Encapsulation in Object Oriented Programming


Encapsulation in Object Oriented Programming

Encapsulation is one of the four fundamentals of the Object oriented programming.

What is Encapsulation?

Encapsulation is a language mechanism to restrict the access of the Objects components to other Objects or Classes. 
Encapsulation helps in enforcing the security of the data related to a particular object. In the programming models like Structural, procedural and Modular programming, there was not much provision to safeguard the data from the other procedures or functions. This can lead to the misuse of data or even the design by responsibility principle of OOAD can be some times breached.
Every Object in Object oriented programming has full control of what members(Fields and methods) to be accessible to its peers in a package, outside the package and should only be visible to its own members alone.
Encapsulation in Object Oriented Programming is implemented by mentioning the Access Modifiers like public, protected, private and default access.
The access to the data  and methods can be restricted to a package, classes level etc.,

Encapsulation with Example

Let me explain the concept of Encapsulation with an example.  Say, you are a student in a class and some of the things you and your friends know, say nick names, should not be revealed to the professors, your parents does not have knowledge of you not attending the classes or poor performance in a subject etc.,
In our own life, we would like to shield/share some information to a group of people. In the same fashion, object as instances of a class has full control of its members. 
When a class is created and its members are defined, the access modifiers are applied to its fields and methods.
When an object is created using that particular class, the access will be restricted based on the defined access of the members.
Encapsulation is nothing but hiding the features that are not relevant for other objects but are essential for their own features.
For Example, I have create a class Car which has two methods:
Encapsulation in Oops
  1. move().
  2. internalCombustion()
The move method depends on internalCombustion() method. But an Employee needs only move method and need not be aware of internalCombustion behavior. So, the internalCombustion behavior can be declared private so that it can be only visible to the members inside the class.

Summary:

Encapsulation is a primary fundamental principle in Object oriented programming. It is used to enforce the security to restrict the visibility of the members to other components. 

Comments

Popular posts from this blog

Approval Process

Spring Batch 2.0 -Basic Concepts

Sending Mass Emails From Salesforce