• RubyonRails
  • JavaScript
  • JSP
  • SQL Tutorial
  • Core Java
  • PHP
  • Spring
  • Java IO
  • jQuery

  • <

    What is Java Encapsulation

    To pack data of a program into a single unit is called encapsulation.The data hidden from other classes can be access using member function,it is also called as data-hiding .

    Data can be accessed using public getter and setter method.in encapsulation the variables in class should be private.


    Java Encapsulation Example



    getset.java
    
    // encapsulation demonstration
    public class Getset
    { 
        // private variables
        // these can only be accessed by public methods of class 
    
        private String sName; 
        private int sRoll; 
        private int skAge; 
      
        // get method for age to access  
        // private variable sAge 
        public int sAge()  
        { 
          return sAge; 
        } 
       
        // get method for name
        // private variable sName 
        public String getName()  
        { 
          return sName; 
        } 
          
        // get method for roll
        // private variable sRoll 
        public int getRoll()  
        { 
           return geekRoll; 
        } 
       
        // set method 
        // private variable
        public void setAge( int newAge) 
        { 
         sAge = newAge; 
        } 
       
        // set method
        // private variable
        public void setName(String newName) 
        { 
          sName = newName; 
        } 
          
        // set method for roll to access  
        // private variable 
        public void setRoll( int newRoll)  
        { 
          sRoll = newRoll; 
        } 
    } 
    
    

    
    public class Test
    {     
        public static void main (String[] args)  
        { 
            Getset obj = new Getset(); 
              
            // setting values
            obj.setName("sanu"); 
            obj.setAge(21); 
            obj.setRoll(100); 
              
            // Displaying values
            System.out.println("name: " + obj.getName()); 
            System.out.println("age: " + obj.getAge()); 
            System.out.println("roll: " + obj.getRoll()); 
              
            // Direct access of geekRoll is not possible 
            // due to encapsulation 
            // System.out.println("sroll: " + obj.sRoll);         
        } 
    } 
    
    

    Java Encapsulation Advantages


  • High Security
  • Reusability
  • Easy to Test
















  • © copyright 2017-2021 Completedone pvt ltd.