Encapsulation

Encapsulation In Java software development language Is one of the OOP fundamental concept. It Is process of packing code and data together In to a single Unit. Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, So anyone can not access private data fields directly outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding. The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives extensibility, flexibility & maintainability to our code. We can use setter and getter methods to get and set data In to It.
setter method : public method which is used to set private field is know as setter method.
getter method : public method which is used to read private value is know as getter method.
Advantages of Encapsulation: - 
* It Increase the usability.
* It promotes the easy maintenance in java software development.
* It makes the class easy to use for clients.
* Data access and modification control.
* It Is easy to change one part of code without affecting other part of code.

Sample Program for Encapsulation :

package encapsulation;

public class Encaps {

         private String name; 
         private int empid;
         
         //Data setter method
         public void setName(String newValue) 
         {
          name = newValue;
         }

         //Data setter method
         public void setEmpID(int newEmpID) 
         {
          empid = newEmpID;
         }

         //Data getter method
         public String getName()
         {
          return name;
         }

         //Data getter method
         public int getEmpID() 
        {
          return empid;
         } 
        }

package encapsulation;
public class exeEncaps {

 public static void main(String[] args) {
  //Created object of Encaps class to set and get data.
  Encaps encaps = new Encaps();
  
  //Set data using setter methods of Encaps class.
  encaps.setName("Purushotham K");
  encaps.setEmpID(12345);
  
  //Get data using getter methods of Encaps class.
  System.out.println("Employee ID   : "+encaps.getEmpID());
  System.out.println("Employee Name : "+encaps.getName());
 }
}

====================

Employee ID   : 12345
Employee Name : Purushotham K

Comments