Tuesday, September 4, 2012

Encapsulation vs Abstraction



Encapsulation
Encapsulation means to capsulate data and the function into a single entity. Encapsulation is the mechanism that binds the code and data together and restricts access by the outside world.

A very good example of encapsulation is a car. All the internal working of the car, its transmission, parts, etc. is hidden from the outside world. Only the important details are mentioned like the size of the tire, number of gears, etc.

You can think of encapsulation as a way to wrap the data inside a container to restrict access from outside world. However, access to the data is provided through a well-defined interface. In java the basis of encapsulation is class. You will specify the code and variables in the form of class variables and methods. The behavior and interface of a class are fully defined by the methods of the class. Access to these methods and variables is specified using the keywords 'public', 'protected' or 'private'. 

  • Public access means anyone can access the data.
  • Private access means only the methods defined within the class can access the data.
  • Protected access means methods within the class and methods within the child classes can access the data.

Child classes are defined using inheritance. 

Thus, encapsulation is hiding of essential details from programmer's point of view



Abstraction
 Abstraction refers to hide all non-essential details from the user and display only the essential part of it. Abstraction is the process of formulating general concepts by abstractingcommon properties of instances.

Abstraction also comes in 2 forms:
control abstraction and data abstraction.

Control abstraction is abstracting the method.
Data abstraction is abstracting the data

Car is a very good example to define abstraction. A person driving the car only needs to know where the gear, clutch, brakes, etc. are present, but he does not need to know how the transmission works, how much fuel is released upon pressing the race, etc.

Abstraction is achieved by forming hierarchical classification or layers. These layers are formed as per the requirement. 

Let us talk about a car where you have 
  1. sound system (as the topmost layer)
  2. radio,cd/dvd player (that works as a second layer) 
  3. system that powers the sound system (last layer)

In java, abstraction is carried out in a way where the object works as the top most layer and all the variables and methods are accessed by it.
  1. Object
  2. Variables and Methods
 With abstraction a user is given a handle to access the data but doesn't need to know anything about the internal working of the system. 

Thus, abstraction is hiding of essential details from the user's point of view





No comments:

Post a Comment