Saturday, 24 August 2013

What is Encapsulation in Java



Encapsulation is major principal of Object Oriented Programming.

Encapsulation is the word which came from the word "CAPSULE" which to put some thing in a kind of shell. In OOP we are capsuling our code not in a shell but in "Objects" & "Classes".  So it means to hide the information into objects and classes is called Encapsulation.





Encapsulation is actually a way of coding in which public methods and private variables are bind into wrapper(Class)  so that Object of that Class can have consistent and correct value.No have have the direct access of class attribute to modify it.Here we Encapsulation can by Information Hiding through private attribute and (Getter ,Setter) method of class.Encapsulation give your Object into a consistent and correct state.
Encapsulation is a way of organizing data and methods into a structure by concealing the the way the object is implemented, i.e. preventing access to data by any means other than those specified. Encapsulation therefore guarantees the integrity of the data contained in the object.


Here is an example of Encapsulation

    public class Employee{
         private String name;
         
         public String getName(){
             return this.name;
         }

         public void setName(String name){
                this.name=name;
         }

    }

In above the Employee class have single private attribute called name and this can be only accessible from outside the class through these getter(getName) and setter(setName).


No comments:

Post a Comment