Data Encapsulation

  1. To encapsulate: to encase in a capsule

  2. If instance variables in the class "myClass" are declared private then all data access from another class must be done through methods that are defined inside "myClass"


    Example:
       public class myClass
        {
          private int Data1;
          private int Data2;
    
          public void myMethod1(...)
           {
             ... This method can access Data1 & Data2
           }
    
          ... more public methods...
        }
    
       public class myProgram
        {
          public static void main(String args[])
           {
             myClass x = new myClass();  // Create an "myClass" object
    
             Program CANNOT access any variable of x !
             
    	 Program must invoke public methods defined inside "myClass" 
    	 to access and manipulate x's variables.
           }
        }
    

  3. The instance variables are then effectively hidden from any one who wishes to use objects of that class...

    All the user can do with object variables of class myClass is invoke methods defined inside myClass

    This process of hiding data is called data encapsulation