Encapsulation:
Before moving into the concept and definition, first of all i would like to ask you one thing. Do you know about capsule (medicine)? Have you seen capsule .?
Everyone has the same answer for the above questions. that is YES
If you know a capsule , definitely you knew about encapsulation.
How a capsule will look like?
As every one knows that the medicine which is wrapped is the capsule.
How Capsule related to Encapsulation:
Just like a capsule(which wraps up medicine) , wrapping up the data is called Encapsulation in OOPS. Encapsulation is a mechanism of hiding the data
( variables/methods ) from the external world.
( variables/methods ) from the external world.
In java a class is the best example of Encapsulation.
How to achieve Encapsulation in Java:
In java, Encapsulation can be achieved by using access specifiers (especially private modifier).
As we know a private access specifier specifies access with in the class (local access), the data can't be exposed to the other classes (in same application or different application).
Let me elaborate this with an example.
CapsulateData is the class with some variables as given below.
As accountNumber, accountName are private variables they can't be accessed outside the class.
If we try to do so, following will be the result.
Here as accountName and accountNumber are private fileds, we can't access them in other classes(not only variables , even private methods also).
From this, we can clearly understood that the data
(accountName , accountNumber ) is hidden by the class from the outside world, which we consider to be encapsulation.