JAVA Core 中有一段话:注意不要编写返回引用可变对象的访问器,今天刚学习了一下,说说我的理解。
运行以下代码,通过修改器setTime修改d,输出harry.getTime会随之改变,因为对象hireday是Date类是一个可变对象,而修改name=”aaa“,输出harry.getName仍然得到harry,而不是“aaa”,因为对象name是String类是一个不可变对象。
也就是说,任何一个引用Date类得到的可变对象都指向hireday,因此修改d值都会引起harry.hireday改变.
- import java.util.Date;
- import java.util.GregorianCalendar;
-
-
-
- public class EmployeeTest {
-
- public static void main(String[] args) {
- Employee harry = new Employee("harry", 10000, 2015, 10, 30);
- Date d = harry.getHireday();
- d.setTime(d.getTime()-1000000);
- System.out.println(harry.getHireday());
-
- String name="aaa";
- System.out.println(harry.getName());
- }
-
- }
- class Employee {
- private String name;
- private double salary;
- private Date hireday;
-
- public Employee(String name, double salary, int year, int month, int day){
- this.name = name;
- this.salary = salary;
- GregorianCalendar Calendar = new GregorianCalendar(year,month,day);
- hireday = Calendar.getTime();
- }
-
- public String getName(){
- return name;
- }
-
- public double getSalary(){
- return salary;
- }
-
- public Date getHireday(){
- return hireday;
- }
-
- public void raiseSalary(double percent){
- double raise = salary*percent/100;
- salary += raise;
- }
-
- }
修正的做法是对可变对象进行克隆
也就是
public Date getHireday(){
return (Date) hireday.clone();
}