Encapsulation

A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data is termed as encapsulation.
     Encapsulation is the word which came from the word "CAPSULE" which to put something in a kind of shell. In OOP we are capsuling our code not in a shell but in "Objects" & "Classes". So it means to hide the information into objects and classes is called Encapsulation.
     Encapsulation hides the implementation details of the object and the only thing that remains externally visible is the interface of the object. (i.e.: the set of all messages the object can respond to).
     Once an object is encapsulated, its implementation details are not immediately accessible any more. Instead they are packaged and are only indirectly accessible via the interface of the object. The only way to access such an encapsulated object is via message passing: one sends a message to the object, and the object itself selects the method by which it will react to the message, determined by functions.
class Loan{
    private int duration;  //private variables examples of encapsulation
    private String loan;
    private Stringborrower;
    private Stringsalary;
   
    //public constructor can break encapsulation instead use factory method
    private Loan(intduration, String loan, String borrower, String salary){
        this.duration = duration;
        this.loan = loan;
        this.borrower = borrower;
        this.salary = salary;
    }
   
    //no argument consustructor omitted here
    
   // create loan can encapsulate loan creation logic
    public Loan createLoan(StringloanType){
  
     //processing based on loan type and than returning loan object
      return loan;
    }
  
}


Post a Comment