Tuesday, March 6, 2007

Encapsulation

It is a process of hiding the implementation details from other classes and just providing a way to access and modify its data.So that ,you can make necessary changes or corrections to your code without affecting or changing the classes that inherits your class.

Consider a situation, where you write a class and your friends inherit it. your class consist of a instance variable declared public as shown below.

class your{
public int size;
}
Now, your friend assigns a value to size , that produces a error in your code.

class friends{
yours y=new yours();
yours.size=-32;
}

Though assigning -32 to size is legal, its bad for you.Because you would be expecting positive values alone. So what will you do now? you would write a setter method that check the value and assigns it to size.

So, there is a need to change your code , as well as your friends code to access the method you have implemented in your class.

This where Encapsulation comes in place.

Benefit of Encapsulation

The ability to make changes in your implementation code without breaking the code of others who use your code is a key benefit of encapsulation.Thus bringing in the Flexibility and Maintainability,and scalability.

In order to do that, Declare your instance variables as private. provide methods to get and set the values of the variable ,like something present in javabeans.

Now lets rewrite your class, so that it is flexible , maintainable , and scalable.

class yours{
private int size;
public int getSize() { return size; }
public void setSize(int x) { //code for checking whether x is positive size=x; }
}

Not only checking, you can also do several other operations, whithout affecting other classes that inherits it.

No comments: