xxxxxxxxxx
- Bundle data and the methods that work on that data in a single unit
- A way to restrict access to components of an object
xxxxxxxxxx
In object-oriented programming, encapsulation refers to the bundling
of data with the methods that operate on that data, or the restricting
of direct access to some of an object's components
xxxxxxxxxx
What is Encapsulation?
Encapsulation is defined as the wrapping up of data under a single unit.
It is the mechanism that binds together code and the data it manipulates.
Another way to think about encapsulation is, that it is a protective shield
that prevents the data from being accessed by the code outside this shield.
xxxxxxxxxx
In general, encapsulation is a process of wrapping similar code in one place.
Encapsulation is one of the key features of object-oriented programming. It involves the bundling of data members and functions inside a single class.
Bundling similar data members and functions inside a class together also helps in data hiding.
Note: People often consider encapsulation as data hiding, but that's not entirely true.
Encapsulation refers to the bundling of related fields and methods together. This can be used to achieve data hiding. Encapsulation in itself is not data hiding.
xxxxxxxxxx
Encapsulation:
Encapsulation is the mechanism of hiding of data implementation by
restricting access to public methods. Instance variables are kept
private and accessor methods are made public to achieve this.
xxxxxxxxxx
What is encapsulation?
Encapsulation protects your code by controlling the ways values are accessed and
changed, so that your code is only used as explicitly designed. Like
abstraction,encapsulation places a layer of separation between the underlying
complexity of your code and the programmers who might be accessing it.
(learn more at link below)
xxxxxxxxxx
class Account:
def __init__(self):
self._transactions = [] # the "_" prefix means treat this as private
def deposit(self, amount):
self._transactions.append(amount)
xxxxxxxxxx
class Account:
def __init__(self):
self._transactions = [] # the "_" prefix means treat this as private
def deposit(self, amount):
self._transactions.append(amount)
xxxxxxxxxx
class Rectangle {
private:
int length;
public:
void setLength(int len) {
if (len >= 0)
length = len;
}
};
xxxxxxxxxx
class Account:
def __init__(self):
self._transactions = [] # the "_" prefix means treat this as private
def deposit(self, amount):
self._transactions.append(amount)