java基礎入門-資料訪問器(set方法)與返回可變對象__set方法

來源:互聯網
上載者:User

今天寫一個大家平常都比較忽略的一個問題

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


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.