Total Pageviews

Wednesday, January 19, 2011

Encapsulation

Classes - Blueprint of an object.
Object- Real world entity.

Constructors in java are always initialized using a new keyword.
 Employee emp("name","salary"); //C++ style not allowed in java
For java use Employee emp = new Employee("name","salary");
Encapsulation - Wrapping of data in a single unit. We provide some methods to change the data
values. Encapsulation if not properly implemented can lead to drastic results. Consider the 
following example :
public class Employee {

   private String name;
   private Date dob;

    public Employee(String name, Date dob) {
        this.name = name;
        this.dob = dob;
    }

    public Date getDob() {
        return dob;
    }

    public void setDob(Date dob) {
        this.dob = dob;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
  
}

Now create an object of this class in some other class.
Date date = new Date(); //System's current date...though cannot be the birth date but after
                          all its an example only :D
date.setHours(10); //Changed one of the values of time to show the output
String name = "amit";
Employee emp = new Employee(name,date);
Now save  the values in objects using getter methods
Date d1 = emp.getDob();
String nameStr = emp.getname();
sout("dob "+ d1.getHours() + " name " + nameStr);//from now onwards all examples will use 
                                                    sout as a terminology for System.out.println();
Output obtained is : dob 10 name amit
Now change the object values d1.setHours(1); nameStr ="xyz";
Now output the values of the employee object
sout("dob "+ emp.getDob().getHours() + " name " +emp.getname());
Strange but output comes out to be "dob 1 name amit"
Note that in the above output the time for dob gets changed to 1. But we havent called the 
setter method for dob. This violates encapsulation. We obtained the above output because 
Date class is a mutable class,so both d1 and emp.Dob refers to the same memory location,
so change by any one gets reflected in the oher object. To avoid this always return a 
cloned object of the mutable classes. In the above case modify the getter method of 
dob as : 
public Date getDob() {
        return (Date)dob.clone();
    }

No comments:

Post a Comment