Encapsulation in Java

In a general language, encapsulation can be termed as “the action of enclosing something in” and in a programming language, encapsulation is used to refer to one of two related but distinct notions, and sometimes to the combination. Encapsulation is the mechanism that binds together code and the data it manipulates and keeps both safes from outside interference and misuse.

One way to think about encapsulation in Java is a protective wrapper that prevents the code and the data from being arbitrarily accessed by other code defined outside the wrapper. Access to the code and the data inside the wrapper is tightly controlled through a well-defined interface.

In Java, the basis of encapsulation is the class. Below is the java program that demonstrates implementation of encapsulation:

In the above program, one can understand that the class Rectangle is encapsulated as the variables are declared as private. The “getters and setters” methods are set as public because they are used to access the private variables declared in the code. They are used because the private variables can’t be accessed directly due to encapsulation.

What are advantages of encapsulation?

  • Encapsulation allows you to change one part of code without affecting the other part
  • It allows you to control who can access what
  • If considering the perspective of testing, encapsulation makes unit testing easy
  • Encapsulation also helps in improving the code reusability
  • Data hiding is also an important feature of it in which one can hide important implementation details and just show rest of it
  • Encapsulation also help us to make a flexible code which can easily be changed or maintained

In spite of so many advantages of it, encapsulation also has a disadvantage, which is you can’t access private data outside class.

Leave a Reply

Contact Us
close slider
Contact Us

How can we help you with?