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.

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!”);
                             System.out.println(“RUFF! RUFF!”);
public class TestDog
          public static void main(String[] args)
                   Dog d1 = new Dog();
                   Dog d2 = new Dog();
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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s


This entry was posted on November 5, 2011 by in How encapsulation is achieved., How to set encapsulation.
%d bloggers like this: