Encapsulation in Java - OOPS concept Explained

Encapsulation is one of the fundamental Object Oriented Programming concepts. In OOPS languages encapsulation is a mechanism of wrapping or bundling the data variable and the method acting on this data together as a single unit. In encapsulation, the class data variable is hidden from other classes and this data variable can be accessed through the method bundled with this hidden(private) data. This is known as data hiding.  

Why need encapsulation?

For example, consider a bank class that has a cash data variable and there is one more class called user that has access to the bank class data variables and methods. Here there is a possibility that the user class access the cash data variable of the bank class and add the money it want, this will lead to big trouble and security issue. So to avoid this vulnerable scenario we follow encapsulation by making the cash data variable private and wrapping it with a  public method getCash() to only read the cash data and restrict write access.



                                           


  1. The data variable of a class can be made read-only or write-only
  2. The owner class will have full control of the data stored in its data variable
  3. In the future class will have the flexibility to change the data type of the variable since the user classes aren't aware of the type of actual data variable 

How to achieve encapsulation?
  • Change the data variable access modifier to private. This private access modifier will provide access within its class only
  • Create public/protected/default get() method
  • Bundle the data and method as a single unit
  • The get() method should return the value of that data variable

Post a Comment

Previous Post Next Post
B