Tuesday, 17 March 2015

Q 08) Encapsulation




         Encapsulation is the methodology of hiding certain data elements of the implementation but providing a public Interface to the client or the user.

(Or)

         It’s basically about hiding the state of an object, with the help of modifiers like, private, public, protected…

(Or)

         Data Encapsulation is wrapping up of information (ie.. attributes and Methods ) within a class .

Eg : A class

Benefits of Encapsulation:
  •  The fields of a class can be made read-only or write-only.
  •   A class can have total control over what is stored in its fields.
  •   The users of a class do not know how the class stores its data.
  •   Specifying members a private can hide the variables and methods.
  •  Objects should hid e their inner workings from the outside view.
  •  Good Encapsulation improves code modularity by preventing objects interacting with each other in an unexpected way.

 Example Program of Encapsulation …

package org.javanoobs.encapsulation;

public class Encapsulation {

     private String name;
     private int id;
    
     // This is the setter method for variable name
     public void setName( String newName){
          
           this.name = newName;
     }
    
     // This is the getter method for varaible name.
     public String getName (){
          
           return name;
     }
    
     //This is the setter method for variable id
    
     public void setId ( int newId){
    
           this.id = newId;
          
     }
     //this is the getter method for variable id
     public int getId(){
           return id;
     }
    
    
}


package org.javanoobs.encapsulation;


public class Main {
    
     public static void main(String[] args) {
          
           Encapsulation enc = new Encapsulation();// object of encapsulation class.
           enc.setId(10000);
           enc.setName(" Danny ");
          
           System.out.println(" Id :  " +enc.getId() + " Name : " +enc.getName());
               
     }

}

OUTPUT :

Id :  10000 Name :  Danny 

No comments:

Post a Comment