Encapsulation:
means grouping up of related members (variables and functions) into a single unit called class.
RealWorldExample:
In our everyday lives, most of us use a video recorder via either the controls on the front of it or via a remote control. We all know which buttons to press in order to watch a program or record a program, this is done via the interface we have with the video recorder. The manufacturer can change the internal workings of the hardware, but this would not often affect us as a user because the interface we have would be the same. That is a play button, a record button, fast forward, rewind, stop, pause, etc.
Coding Encapsulation
The following code demonstrates a class containing some data and a method that acts upon the data (without data hiding):
class Counter
{
public int Count;
public Counter()
{
Count = 0;
}
public void incCount()
{
Count++;
}
}
Although the member variable can be directly accessed, the data and its method is encapsulated in a class.
DataHidding:
Data hiding is linked to encapsulation; however data hiding is not encapsulation as it is sometimes described in this way.
Data hiding is simply the means to remove direct access to an object’s information, by providing operations that perform actions on the data. This way any changes to the value of the data must come through the interface to the data, which is an operation. Thus we use access operations or properties.
An Example
In our person object, access to the data forename is supplied through the access operations set forename() and get forename().
Coding Data Hiding
The following code demonstrates a class containing some data that is hidden:
class Counter
{
private int Count;
public Counter()
{
Count = 0;
}
public void setCount( int newVal )
{
Count = newVal;
}
public int getCount()
{
return Count;
}
}
This piece of code is also encapsulated, showing that you can have encapsulation without data hiding, but you cannot have data hiding without encapsulation.
Abstraction:
As to abstraction, it's a philosophical category which you should be familiar first. In programming, this is… all you do in programming. When you create a method, this is abstraction, because you abstract out of the idea of doing some code here and not and allow to call it from many places. When you add a method parameter, you abstract the method out of the hard-coded value. Every type is abstraction, etc.