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.
Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

Information

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

Browse blog by date

November 2011
M T W T F S S
« Oct   Dec »
 123456
78910111213
14151617181920
21222324252627
282930  

Blog Stats

  • 1,105 hits
%d bloggers like this: