Advantages and Disadvantages of Encapsulation in Java

The word “Encapsulation” means that closing something like we put the main power of the tablet inside the capsule. It is a mechanism that is done to bind the data and protect it from being used by everyone.

After doing encapsulation, the variables and the data of one class cannot be used in another class and this data can be used by the member functions of the same class. Encapsulation can be achieved by adding the private specifier to the variables.

See the below example of how encapsulation can be done:

Advantages of Encapsulation

  • Data Protection: The program runner will not be able to identify or see which methods are present in the code. Therefore he/she doesn’t get any chance to change any specific variable or data and hinder the running of the program.
  • Flexibility: The code which is encapsulated looks more cleaner and flexible, and can be changed as per the needs. We can change the code read-only or write-only by getter and setter methods. This also helps in debugging the code if needed.
  • Reusability: The methods can be changed and the code is reusable.

Disadvantages of Encapsulation

  • Code Size: The length of the code increases drastically in the case of encapsulation as we need to provide all the methods with the specifiers.
  • More Instructions: As the size of the code increases, therefore, you need to provide additional instructions for every method.
  • Increased code execution: Encapsulation results in an increase in the duration of the program execution. It is because more instructions are added to the code therefore they require more time to execute.

So these were the advantages and disadvantages of encapsulation. Comment down below if you have any queries.

Leave a Reply

Your email address will not be published.