Thursday, 26 December 2013

Why we need encapsulation in Java?

Why we need Encapsulation in Java ?

Suppose many programmer in your company wrote program that used your class.Now imagine later on you want to change an instance variable's value because the value set(by some other programmer using you class) to those variable are producing errors for you. Lets take an example

your class Demo1
{
int age;
getCalculatedAge()
{
//Code for calculation of age
}
}

Now suppose another programmer using your code

Demo2()
{
Demo1 d1=new Demo1();
d1.age= -4; // Suppose this causes some problem
d1.getCalculatedAge();
}
And now you're in trouble. How are you going to change the class in a way that lets you handle the issues that come up when somebody changes the age variable to a value that causes problems?

Your only choice is to go back a write a method setAge(int) for getting the age and handle the problem as well as you have to protect your age variable with private access modifier.

But as soon as you make your changes you break everyone else's code.

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.

If you want maintainability, flexibility, and extensibility (and of course, you do),your design must include encapsulation. How do you do that?

1. Keep instance variable protected (e.i private )
2.Make public setter or getter method so you can access and set the value to those variable.

public void setAge(int a)
{
age=a;
}
 
public int getAge()
{
return age;
}

This will prevent the direct access of your instance variable.Wait a minute...how useful is the previous code? 

Now what benefit can be there from getter and setter, Now in future if you want any processing or validation while getting the age from the setAge method you can do that without affecting anyone else's code which are using your class. Even if today you don't think you really need validation or processing of the data, good OO design dictates that you plan for the future. To be safe, force calling code to go through your methods rather than going directly to instance variables. Always. Then you're free to rework your method implementations later, without risking the wrath of those dozen programmers who know where you live.

No comments:

Post a Comment