Java Encapsulation

    Encapsulation

    Java supports the Encapsulation method that allows you to wrap the code and the data together within a single unit just like a capsule. You can use the private access modifier to make the encapsulated class in Java. you can easily set and get the data using setter and getter methods. For example- Java Bean.

    Encapsulation Features-

    • You can make any class read-only or write-only by using getter and setter method.
    • It allows you to control the data stored by providing logic within the setter method.
    • It allows the data hiding as other class would not be able to access the private data members of other class.
    • It allows for easy unit testing.

    Example-

    Pack file-

    package Simple_pack;  
    
    public class Pack{  
        private int var;
    
       public int getVar(){
          return var; }
    
       public void setVar(int v)
       { 
           var=v;
        }
    }  

    Simple file-

    package Simple_pack;
    
    //import demo_pack.*;
    
    class Simple {
    
    public static void main(String args[]){  
    
       Pack d=new Pack(); 
    
    d.setVar(6);
    
    System.out.println(d.getVar());
      }  
    } 

    Output-