今天寫一個大家平常都比較忽略的一個問題
set方法與返回可變對象
我們平常在編程的時候,大部分的時候都是使用get、set方法來訪問或者設定屬性域
但是在set的方法當中會出現一些比較特殊的例子,就像下面的代碼,
birthday手型,在set方法裡面返回的是一個可變對象date,然後我們再通過這個date去改變屬性域裡面的值
這種錯誤時經常出現在代碼裡面,正確的做法是在birthday的set方法裡面加入clone方法,這樣就保證了屬性域的不可操作性
package com.ray.object;import java.text.SimpleDateFormat;import java.util.Date;/** * 資料訪問器(set方法)與可變對象 * * @author ray * @since 2015-04-22 * @version 1.0 * */public class Person {private Date birthday = new Date();// 注意:這裡返回的是可變對象public Date getBirthday() {return birthday;}public static void main(String[] args) throws Exception {Person bill = new Person();System.out.println(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(bill.getBirthday()));Date birthday = bill.getBirthday();Thread.sleep(2000);birthday.setTime(System.currentTimeMillis());System.out.println(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(bill.getBirthday()));}}
輸出:
2015-04-27 09:23:29
2015-04-27 09:23:31
正確的代碼:
package com.ray.object;import java.text.SimpleDateFormat;import java.util.Date;/** * 資料訪問器(set方法)與可變對象 * * @author ray * @since 2015-04-22 * @version 1.0 * */public class Person {private Date birthday = new Date();// 注意:這裡返回的是可變對象public Date getBirthday() {return (Date) birthday.clone();}public static void main(String[] args) throws Exception {Person bill = new Person();System.out.println(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(bill.getBirthday()));Date birthday = bill.getBirthday();Thread.sleep(2000);birthday.setTime(System.currentTimeMillis());System.out.println(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(bill.getBirthday()));}}
輸出:
2015-04-27 09:25:36
2015-04-27 09:25:36