Thursday 26 February 2015

Encapsulation in Java

       Encapsulation is the concept of hiding/restricting data to access from outside . Encapsulation provides the attribute access control. The access control can be achieved through access specifiers.

There are 4 access specifiers in Java
1)public
2)private
3)protected
4)default

Public:
   If you use public as access specifier then you can access those members of a class from outside the class/package also.

Private:
     If you use private access specifier then you cannot access those members of a class outside the class . it will be accessible only within that scope.
We will discuss later about the scope of an instance.

Protected :
     The protected access specifier behaves as private to outside but it will allow to access the members in inherited classes .

We will discuss more about protected with example in the section Inheritance.

default:  
      If you declare any members of a class without any access specifier i.e public,private,protected then it will consider the member as default . It is a private access specifier will allow to access the members of the class only inside that class.
Note: default is not a keyword to specify the access specifier. If you not mention the access specifier then it will be considered as default.

Example:
To copy the code you can select the code and ctrl+C


Output :
with out private variable access outside the class







 Error if you try to access private variable in another class







No comments: