Overview to Encapsulation and Abstraction

10:53 PM Shashank Tiwary 0 Comments

Object oriented programming has many major building blocks in which you find Encapsulation and Abstraction. These two properties are compulsory unit of OOP languages. These properties are not very much differed together but they are different in many respect. Now from here I am going to describe you these properties one by one.

Encapsulation, as all we know that is a property of encapsulating data into a program. Know you must think of that, what data we are going to capsulate, why we do it and how can we do it. For the answer let’s look at a practical scenario.

Suppose you have a responsibility to make stack to store user’s data. Now you create a stack class which contains a member variable ‘Start’ which keeps track to the starting point of stack. Consider the code is given below,

Class Stack

{

ArrayList al=new ArrayList();

public Node Start;

public Stack(){

this.Start=al[-1];

}

public push(Node n){// push operation}

public pop(){//pop operation}

}

Now suppose other programmer use your class and he/she mistakenly change the Start variable of your class that can cause your class to be malfunction. So to make you class bug free as well as other programmer can have access to read the Start variable of you class you must encapsulate the data from the client programmer. The below code will show you how to do that,

Class Stack

{

ArrayList al=new ArrayList();

private Node Start;

Public Stack(){

this.Start=al[-1];

}

public push(Node n){// push operation}

public pop(){//pop operation}

public Node START // Encapsulating data Now other programmer use this property to read Start

{ // Variable of this class

get

{

return Start;

}

}

}

“Now we can say that Encapsulation is the way of hiding data but still giving a public interface to access within it.” After all we come to the next topic which is Abstraction. In very simple words abstraction is property which hides the methods of a class from another class. So the classes which inherit these classes must override abstract methods before use. This property is back bone in creating SDKs and Frameworks.

0 comments: