Topics Index

Object Oriented Concepts - Revisited >
Siva Nookala - 14 Apr 2016
Encapsulation is the mechanism that binds together code and the data it manipulates and keeps both safe from outside interference and misuse. Encapsulation is one of the three object oriented concepts.

A good example of encapsulation is how the local shop keeper gives the items we requested for, weighs and packages them and collects money. Imagine what will happen if the shop keeper is not there and we go into the shop and find the items we want, weigh them as needed and put the money in the cash box. Encapsulation is also how we store the related data and the owner of that data in one place. Imagine a situation where we go to the shop keeper's house to order, go to the shop to pick it up and pay the money in bank. Then the simple process of buying a small item could become very complex.

Similarly, as seen in the program in Using private Keyword In Java For Access Control , the student marks could be misused if the data storing the marks is not properly protected. If we encapsulate them completely by making all the variables as private, then we can not change the marks. But if we don't then the marks and the total_marks could become inconsistent. So we need a controlled way of changing the marks, with out the data becoming inconsistent.

Since in Java, encapsulation is supported by classes, it is necessary for us to create the classes by grouping the right data and its behavior, provide the required functionality and at the same time prevent misuse and outside interference.

Dependent Topics : Abstraction in Java 

Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App