Wednesday, April 16, 2014

Object Oriented Programming, Part 4 - Encapsulation

Encapsulation
The literal meaning of encapsulation is to encase the things together like capsule.
Same way, In OOPs encapsulation is the process of binding data members( variables) and member functions(methods) into single unit. In that case defining a class in java is best example.

In Object Oriented Programming we need to focus on the proper encapsulation. To achieve proper encapsulation the access modifier plays a vital role. To know about access modifier follow my post,Access Modifier .

Why we need proper Encapsulation?
When we work on any application, we will not be the single developer working on that.
Now consider the following code:

package in.technoscience;

public class WrongEncapsulation {

 public int age; // an instance variable with public access modifier.
 public String name;
}
now suppose other developer use your code like as below :

package in.technoscience;

public class Testing {
public static void main(String[] args) {
 WrongEncapsulation we= new WrongEncapsulation();
 we.age=-6; // its legal no complain from compiler but its bad
 System.out.println(we.age);
}
}
From above code the other developer can access the class variable and can modify that, here other developer accessed the age instance variable directly and change its to negative value, so in any case does negative age makes any sense?

Now to achieve the proper encapsulation, we need to follow following steps:
  • use private access modifier with the instance variables.
  • to access those instance variables, use the public methods, in terms of java we called those methods as setter and getters. To write those methods we use JavaBean naming convention.
Improving the above code:

package in.technoscience;

public class ProperEncapsulation {

 private int age;// private instance variable
 private String name;
 public int getAge() {// setter and getters methods to access instance variable
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }

Summary:
  1. Encapsulation helps to write more flexible and maintainable code
  2. Encapsulation helps to bind all  variables and methods into single unit called as class
  3. Encapsulation provides an ability to make changes in our implementation code without breaking the code of others who use our code.
  4. Encapsulation solves the problem at implementation level and hide the implementation and protect the data from outer world (which can modify our code) using access modifier.

No comments:

Post a Comment