Encapsultaion
Encapsultaion
ENCAPSULATION
WHAT IS ENCAPSULATION?
● Encapsulation is a
process of combining
data and functions into
a single unit called
class.
● Encapsulation is
technique of making
fields in a class private
and providing access to
EXAMPLE CODE
#include<iostream.h>
using namespace std;
class Encapsulation
{
private:
int x;
public:
void set(int a)
{
x=a;
}
void get()
{
return x;
}
};
int main()
{
Encapsulation obj;
cout<<obj.x; //Error!
obj.set(5); //Correct way!
cout<<obj.get();
return 0;
}
Why Is Encapsulation
Important?
Flexibility: It’s more flexible and easy to change the encapsulated
code with new requirements. For example, if the requirement for
setting the age of a person changes, we can easily update the logic
in the setter method.
Reusability: Encapsulated code can be reused throughout multiple
applications. For example, the Person class can be reused
whenever such type of object is required.
Maintainability: Code is encapsulated in separate units (classes,
interfaces, methods, setters, getters, etc) so it’s easy to change or
update a part of the application without affecting other parts, which
reduces the time of maintenance.
Difference between Abstraction
and Encapsulation
● Encapsulation means
● Abstraction lets you focus
hiding the internal details
on what the object does
or mechanism of how an
instead of how it does.
● It solves the problem in object does something.
● It solves the problem in
Design level.
● Ex: Outer look of a mobile Implementation level.
● Ex: Inner implementation
phone, like it has a display
detail of a mobile phone,
screen and keypad buttons to
how keypad button and
dial a number.
display screen are
connect with each other
using circuits.
Advantages of Encapsulation
● To allow one class(“server”) to make a
interact with another class(“client”).
● Data and function may be public or private.
● It hides the complexity from the
implementation.
● It also provides inter independencies.
● A class can have total control over what is
stored in its fields.
Use Case: