Monday, September 23, 2013

Simple Encapsulation in Java

Last week I was taught about Encapsulation by my teacher.I've been knowing encapsulation when i started to read e-book java which is SCJP for Java 6.That's a good book to understand deeper about java.I suggest you to read the book.

Today i'm gonna show you how to make your class to use encapsulation concept.First of all you have to understand why we must use encapsulation.Sometimes you create a class and you don't want some fields to be accessed by other class.There is a way to make your field cannot be accessed.You can use access modifier "private".Look at the code example :

public class Vechicle
{
    private int wheels; // the field of wheels value is 0 implicitly
}
You can see that wheels have access modifier "private" that means it cannot be accessed by other class except the class itself.When you create vechicle object you will get the value of wheels is 0.It's the default value for type data int.

The following chart summarizes the default values that will be assigned automatically


if the access modifier is private how we can initialize a value.You can use a method that is access modifier "public" to get or to set the value.That is called encapsulation.You hide your field and then making a method to get and to set the value.So if other class want to access the field they have to access public set/get method.I'm gonna edit the above code into this :
public class Vechicle
{
   private int wheels; // the field of wheels value is 0 implicitly

   public void setWheels(int wheels)
   {
      this.wheels = wheels; // keyword "this" refers 
                            // to current class Vechicle
   }

   public int getWheels()
   {
      return wheels;
   }
}
Now we have class vechicle that use encapsulation.This is the code main to access wheels field.
public class Main
{
   public static void main(String[] args)
   {
       Vechicle v = new Vechicle(); // You create vechicle object
       System.out.println
           ("Wheels before initialization " + v.getWheels() );
       v.setWheels(4); // initializion value
       System.out.println
           ("Wheels after initialization " + v.getWheels() );
       v.wheels = 2; // cannot access "private" access modifier
   }
}
If you still don't understand you can comment here :D

3 comments:

  1. ven ini ang pake bahasa indonesia aja apa ndk ada seh? T.T sudah mkir mask mkir lagi dua kali :P hehehe...

    ReplyDelete
    Replies
    1. Biasakan menggunakan bahasa inggris zhar.Gampang kok sering dilatih aja setiap hari :D

      Delete
  2. wkwkwk.... but not all of people want do something twice and difficult... :P

    ReplyDelete