在看《Java核心技术(原书第9版中文版)》的时候,看到113页的一个警告,“注意不要编写返回引用可变对象的访问器方法”。以前没看到过,原来Date对象是可变对象。就可变对象这个概念,查了一下网,我认为可变对象,就是在类中可以不通过域更改器方法就能改变值的对象。
1 package com.csst.sort; 2 3 import java.util.Date; 4 import java.util.GregorianCalendar; 5 6 public class Employee { 7 private String name; 8 private double salary; 9 private Date hireDay; 10 11 public Employee(String n, double s, int year, int month, int day) { 12 name = n; 13 salary = s; 14 GregorianCalendar Calendar = new GregorianCalendar(year, month - 1, day); 15 hireDay = (Date) Calendar.getTime(); 16 } 17 18 public static void main(String[] args) { 19 20 Employee employee = new Employee("lele", 600, 1994, 10, 24); 21 22 Date date = employee.getHireDay(); 23 System.out.println(date); 24 25 date.setTime(2000500000); 26 27 System.out.println(date); 28 System.out.println(employee.getHireDay()); 29 } 30 31 public void raiseSalary(double byPercent) { 32 double raise = this.salary * byPercent / 100; 33 salary = this.salary + raise; 34 } 35 36 public String getName() { 37 return name; 38 } 39 40 public void setName(String name) { 41 this.name = name; 42 } 43 44 public double getSalary() { 45 return salary; 46 } 47 48 public void setSalary(double salary) { 49 this.salary = salary; 50 } 51 52 public Date getHireDay() { 53 return hireDay; 54 } 55 56 public void setHireDay(Date hireDay) { 57 this.hireDay = hireDay; 58 } 59 60 }
最终结果:
Mon Oct 24 00:00:00 CST 1994
Sat Jan 24 11:41:40 CST 1970
Sat Jan 24 11:41:40 CST 1970
说明hireDay已经改变,将其get方法改为
public Date getHireDay() { return (Date) hireDay.clone(); }
结果为:
Mon Oct 24 00:00:00 CST 1994
Sat Jan 24 11:41:40 CST 1970
Mon Oct 24 00:00:00 CST 1994
时间: 2024-10-09 05:30:08