Jan
07
Defensive copying is used for protecting the field of an object from being changed by all non native class. Sometimes if we do not use defensive copying our object may hold incorrect data. For eg:
import java.util.*; public class Test { private Date today; public void setToday(Date dt) { this.today = dt; } public Date getToday() { return today; } public static void main(String args[]) { Test t = new Test(); Date dt = new Date(); t.setToday(dt); System.out.println("Actual :: " + t.getToday()); dt.setYear(2000); System.out.println("Current :: " + t.getToday()); } } |
The output of the above program will be.
Actual :: Mon Jan 07 12:29:43 IST 2008
Current :: Sun Jan 07 12:29:43 IST 3900
In the above program changing the dt object changes t object data also. To prevent this we use defensive copying. The fix for this will be to create a defensive copy of the object in the setter. For eg:
public void setToday(Date dt) { this.today = new Date(dt.getDate()); } |
Now if we run the program the output will be
Actual :: Mon Jan 07 12:29:43 IST 2008
Current :: Mon Jan 07 12:29:43 IST 2008


