Who Knows All.. ?

If the answer is No one. Then this blog is for U. I'm going to put all the things I know in Java

How exactly do I encapsulate the data?

With the public and private access modifiers. Mark your instance variables ‘private’ and provide setter and getter methods for access control. 
Example program:
Let say you have Dog class. You can create any numbers of instances of it. Dog can bark. Depending on the size of the Dog, it barks differently.
Program:

public class Dog
{
          private int size;

          public int getSize()
          {
                   return size;
          }
          public void setSize(int s)
          {
                             size = s;
}
public void bark()
          {
                   if(size>1 && size<16)
                   {
                             System.out.println(“WOOF! WOOF!”);
}
                    if(size>15)
                   {
                             System.out.println(“RUFF! RUFF!”);
                   }
          }
}
public class TestDog
{
          public static void main(String[] args)
          {
                   Dog d1 = new Dog();
                   d1.setSize(10);
                   Dog d2 = new Dog();
                   d2.setSize(25);
                   d1.bark();
                   d2.bark();
          }
Now in this program you have created two Dog instances(objects) with sizes 10 and 25 respectively. But setSize method  force the user to give the size. And in Dog class you have set the conditions for a Dog size. If the user has set the dog size to let say 0(zero) which is inappropriate ,even though it(the program) compiles and runs it wont give any output(or you can show some message to the user if you want). Likewise you can make your code pass through some conditions. Thus encapsulation is achieved.

Leave a comment

Information

This entry was posted on November 5, 2011 by in How encapsulation is achieved., How to set encapsulation.