Thursday, June 17, 2010

Java Interview Question 6

<< Previous                                                                                    Next  >>

Java Interview Question 16:
What is encapsulation?

Imagine a class, RectExample with public instance variables as the following code demonstrates:

public class RectExample {
public int length;
public int breadth;
...
}

Since the instance variables of RectExample are public, another programmer can easily modify the instance variables in a way that helps their code logic but totally alters the way your class works:
public class AnotherRectExample {
   public static void main (String [] args) {
      RectExample b = new RectExample ();
      b.length = -5; // Legal but not good!!
  }
}





In the above code another programmer is trying to set a value to the length variable that you dont want. So we need to make changes to the class in such a way that no one can alter the values directly. The ability to make changes in your code without breaking the code of all others who use your code is a key benefit of encapsulation. This can be achieved by making the instance variables as private and then have a set of public methods that others can use to access the variables. The access methods are referred as getters and setters or accessors and mutators. Declaring variables as private in a class, gives access to the variables to only member functions of the class. A next level of accessibility is provided by the protected keyword which gives the derived classes the access to the instance variables of the base class.
Example:
public class SquareExample {
// protect the instance variable only an instance of your class can access it
private int length;
// Provide public getters and setters
public int getLength() {
return length;
}
public void setLength(int newLength) {
length = newLength;
}
}

Encapsulation can be defined as the technique of making the fields in a class private and providing access to the fields via public methods. The main benefit of encapsulation is the ability to modify your implemented code without breaking the code of others who use your code. With this feature Encapsulation gives maintainability, flexibility and extensibility to your code.
<< Previous                                                                              Next  >>

No comments: