天天看点

访问器中谨慎返回引用类型对象

面向对象三大特性之一是封装,类中的域(变量),尽量使用private,如果真要访问,可以提供get和set,以避免破坏封装性。

但是,如果get访问器中返回的是引用类型对象的话,那也有可能会被外界所修改,从而破坏封装性。如:

public class Employee {
  private Date hireDay;
  public Date getHireDay(){
    return this.hireDay;
  }
  
  private String name;
  public Employee(String name){
    this.name = name;
  }
  public boolean equals(Employee other){
    return name.equalsIgnoreCase(other.name);
  }
}      
Employee zhang3 = new Employee("zhang3");
    Date d = zhang3.getHireDay();
    d.setTime(d.getTime() - 10000000);      

继续阅读