Wednesday, 27 June 2012

Encapsulation & Abstraction

Encapsulation: Encapsulation is defined as a process of wrapping methods and variables as a single entity or unit (whatever you prefer calling it ... )
In simpler terms:
1.   Class A  
2.   {  
3.    private int value;  
4.    public int getValue(){  
5.      // Implementation code -- Which remains hidden!!!  
6.      return value;  
7.    }  
8.   }  

Imagine around 1000 classes using the above class. Now what if I rename the variable value to integerValue, The code will surely not break because the only way to access the value of the variable value is via the method getValue and thus any changes made to the variable will not break the code. This thus defines encapsulation as a process of wrapping methods and variables as a single unit (I prefer calling it a UNIT).This actually is an example of Strong Encapsulation.

Abstraction: Abstraction is defined as a process of hiding implementation data from the usage area.

One good example of abstraction in Java is its support for multi-threading. I'm almost certain that under the hood, there is a complicated process of allocating and deallocating this and that, timers and schedulers, gears and motors whirring and buzzing, all in all some pretty heavy-duty computing. I say almost certain because I've never looked, and don't want to if I don't have to. Lucky for me, the Thread class and Runnable interface abstract all that business away from me. All I have to know is how to implement the Runnable interface, and how to pass that to a Thread and call start().