Encapsulation in Java

Photo by Thomas Franke on Unsplash

Is it use for data hiding? Yes it is Encapsulation is data hiding. But what is the point of hiding data.

  • Encapsulation limits the access for data.

Some cases we need to provide read only access for that we use encapsulation. Let’s take an example — For a student, student id should not be able to change after it assigned as follows. Then we have to make that variable private and make a method to read it. Then it cannot be changed.

Should we need to use get word as a prefix to get data? No. But it is a good practice.

  • Encapsulation helps to logically access the data.

In some cases we have to set limits or set the variables according to some conditions then we can use encapsulation to provide method to modify the variable as follows.

Hopefully this is helpful.

If you have found this helpful please hit that 👏 and share it on social media :).

Technical Writer | Tech Enthusiast | Open source contributor