05 October 2010

0 What is Encapsulation in Java OOP

The Encapsulation, an object-oriented concept can be correlated with either data hiding or data bundling.

In an object-oriented concept, encapsulation is used to refer to one of two related but distinct notions, and sometimes to the combination thereof:
  1. A mechanism for restricting access to some of the object's components (Access restriction to the variables of an object using the "private", "protected", "public" etc).
  2.  A mechanism that facilitates the bundling of data with the methods(functions) operating on that data (Think about an object with some private variables and some public getter and setter methods).

The second definition is motivated by the fact that in many OOP languages hiding of components is not automatic or can be overridden; thus information hiding is defined as a separate notion by those who prefer the second definition.
    Consider the case of Java, we can implement various levels of access restrictions using "private", "protected" or "public", So Encapsulation is always not about data hiding.
Encapsulation is the process of binding code and data together in the form of a capsule.

Java Example for Encapsulation
Consider a class Stack, the data could be stored in an array which will be private.
  • The methods push and pop will be public.
  • A program cannot access the array directly from outside the class.
  • A program can access the array indirectly through the push and pop methods.
          In other words, Encapsulation can be defined as the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse. The data is not accessible to the outside world and only those functions that are wrapped in the class can access it. These functions provide the interface between the object’s data and the program. The insulation of the data from the direct access by the program is called data hiding.
         In OOP, code and data are merged into an object so that the user of an object can never peek inside the box. This is defined as encapsulation (i.e. Object is a capsule encapsulating data and behavior). All communication to it is through messages (i.e function calls which we use to communicate to the object). Messages define the interface to the object. Everything an object can do is represented by its message interface.


0 comments:

Feeds Comments

Please give your valuable comments.