Saturday, April 26, 2014

# 13 - Why private when we have public access in Java?

Hello,

In previous posts, we have seen what and how Java Access Modifiers can be used. In this post you are gonna see about WHY,
  • should we restrict the visibility of class members?
  • should we choose private/protected when we have public?
  • shouldn’t we use public for all the class members ?

More or less all the above questions have same answer.. :P So let’s get into the topic.

We know that, a class can ONLY have either public or default access. JVM doesn’t allow us to make a class private/protected. Here the BIG question comes, WHY? Answer is pretty simple (because I know..:P) Our Java ancestors didn’t  find any sense in making a class private or protected. We create something to make use of it, not to hide it. The same applies to Java class as well.
So one point is clear, the restriction rule applies only for class members not for the entire class. Lets see an example to find out what is the harm in declaring all the class members as public.
//ClassA
public class ClassA {
 
 public String animalName;
 public int weight; 
}

//ClassB
class ClassB{
 public static void main(String... s){
   ClassA a1 = new ClassA();
  
   // Developer 1
   a1.animalName = "Dog";
   a1.weight = 15;
  
   // Developer 2
   ClassA a2 = new ClassA();
   a2.animalName = "Cat";
   a2.weight = -10;   // Oops..! weight cannot be a Negative number :O
 }
}
You can see that I have a class ClassA whose class members are all public. So ClassB has imported ClassA and used the ClassA variables by creating the object of ClassA. Developer 2 has assigned a negative value to the weight variable which causes an issue/bug in the project. If the weight variable is public, anyone can access it and changes to a value that causes problem. So I have to restrict other developers from assigning bad values to the instance variables. 
Here comes the great concept and one of the very very very important OOP’s features - Encapsulation.

So let’s see what is Encapsulation and how it is helpful to avoid the issue explained above.
//ClassA
class ClassA {
 
 private String animalName;
 private int weight;
 
 // getters and setters
 public String getAnimalName() {
  return animalName;
 }
 public void setAnimalName(String animalName) {
  this.animalName = animalName;
 }
 public int getWeight() {
  return weight;
 }
 public void setWeight(int weight) {
  // if the weight is less than zero, then assign zero
  if(weight < 0)
   weight = 0;
  this.weight = weight;
 }
}

//ClassB
public class ClassB{
 public static void main(String... s){
  
   // Developer 1
   ClassA a1 = new ClassA();
  
   a1.animalName = "Dog"; // this gives compiler error. 'cause animalName variable is private. 
  
   // to set the values
   a1.setAnimalName("DOG");
   a1.setWeight(15);
  
   // to get the values
   System.out.println("Animal 1 Name --> "+a1.getAnimalName());
   System.out.println("Animal 1 Weight --> "+a1.getWeight());
  
   // Developer 2
   ClassA a2 = new ClassA();
    
   // set the values
   a2.setAnimalName("CAT");
   a2.setWeight(-10);
  
   // get the values
   System.out.println("Animal 2 Name --> "+a2.getAnimalName());
   System.out.println("Animal 2 Weight --> "+a2.getWeight());
 } 
}
In the above program you can see that, Developer 2 has assigned a negative number to the weight by using setWeight(int weight). In this method, we are doing the validation (set zero if the weight is negative) to the weight variable which saves us from occurring a bug/issue. Now we are safe irrespective of how other developers use this ClassA. Run the above program and you get the output as,
Output:

Animal 1 Name --> DOG
Animal 1 Weight --> 15
Animal 2 Name --> CAT
Animal 2 Weight --> 0
See that, Animal 2 Weight is zero but the Developer 2 has assigned the value -10.
The bottom line is – making the instance variables private and getters/setter methods public provides us a space to validate the instance variables. So that the developers are forced to use getters/setters to access instance variables. This is one of the biggest benefits of Encapsulation.
In simple words, we encapsulate the instance variables with the help of getters/setter methods. This is Encapsulation.

So I believe now you got the answers for all the above questions and also I am sure you have been using this Encapsulation feature in your projects. You have probably been using the Java Bean Classes as shown below,
class ClassA {
 
    // protect the instance variables
    private String animalName;
  
    // provide public getters and setters
    public String getAnimalName() {
  return animalName;
    }
    
    public void setAnimalName(String animalName) {
 this.animalName = animalName;
    }
}
You might not have asked yourself how useful this class is. So what is the benefit in making instance variables private and having getters/setters when there is no validation/functionality?
We do have lot of benefits in having getters/setters even though if there is no validation/functionality.
  1. I can change my mind later and add more code to the methods. So that no other developer who is trying to access the instance variables are not affected.
  2. Today we don’t thing we really need any validation to the instance variable but in future we might want to add the validation and these getters/setters helps us without breaking other code/logic.
  3. A good OO Design of a project should be something that we plan for future so that the future modifications don’t break the existing code.

To be safe, force calling code to go through the methods rather than accessing instance variables directly. Always..!!

Hit Points:

  1. In practice, its best to keep all variables private or protected. If the value of variables need to read or changed, programmers should use public access methods so that any other class should use get/set methods rather than accessing them directly.
  2. 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.
  3. Encapsulation helps hide implementation behind an interface.
:)

0 comments:

Post a Comment