Write today a question that we all generally overlook
Set method and return mutable object
We usually use the get, set method to access or set the property field when we are programming.
But there are some very special examples in the Set method, like the following code,
Birthday, the Set method returns a Mutable object date, and then we use this date to change the value in the property field.
This error often occurs in the code, the correct approach is to add the Clone method inside the birthday set method, so that the property field is not operable
Package com.ray.object;
Import Java.text.SimpleDateFormat;
Import java.util.Date;
/**
* Data Accessor (set method) and Variable Object
* *
@author Ray
* @since 2015-04-22 *
@version 1.0
*
* * * public class Person {
private Date birthday = new Date ();
Note: The variable object public
Date Getbirthday () {return
birthday
}
is returned here. public static void Main (string[] args) throws Exception {who
bill = new Person ();
System.out.println (New SimpleDateFormat ("Yyyy-mm-dd hh:mm:ss")
. Format (Bill.getbirthday ());
Date birthday = Bill.getbirthday ();
Thread.Sleep ();
Birthday.settime (System.currenttimemillis ());
System.out.println (New SimpleDateFormat ("Yyyy-mm-dd hh:mm:ss")
. Format (Bill.getbirthday ());
Output:
2015-04-27 09:23:29
2015-04-27 09:23:31
The correct code:
Package com.ray.object;
Import Java.text.SimpleDateFormat;
Import java.util.Date;
/**
* Data Accessor (set method) and Variable Object
* *
@author Ray
* @since 2015-04-22 *
@version 1.0
*
* * * public class Person {
private Date birthday = new Date ();
Note: This returns the Mutable object public
Date Getbirthday () {return
(Date) Birthday.clone ();
}
public static void Main (string[] args) throws Exception {who
bill = new Person ();
System.out.println (New SimpleDateFormat ("Yyyy-mm-dd hh:mm:ss")
. Format (Bill.getbirthday ());
Date birthday = Bill.getbirthday ();
Thread.Sleep ();
Birthday.settime (System.currenttimemillis ());
System.out.println (New SimpleDateFormat ("Yyyy-mm-dd hh:mm:ss")
. Format (Bill.getbirthday ());
Output:
2015-04-27 09:25:36
2015-04-27 09:25:36