对象的数据域的值,为了保证封装性,一般设置为私有的数据域,然后通过共有的访问器和更改器进行更改。然而,当一个访问器返回引用可变对象,就会出现错误,破坏其封装性。举例子如下
package chapter4;
import java.util.Date;
public class TestEmployee {
public static void main(String[] args) {
Employee[] staff = new Employee[2];
staff[0] = new Employee("duan",new Date());
staff[1] = new Employee("error!",new Date());
System.out.println(staff[0]);
System.out.println(staff[1]);
long tenmillons = 10*365*24*60*60*1000;
staff[1].getdate().setTime(staff[1].getdate().getTime()-tenmillons);
System.out.println(staff[1]);
}
}
class Employee{
private String name;
private Date hire;
Employee(String name,Date hire){
this.name = name;
this.hire = hire;
}
public String getname(){
return name;
}
public Date getdate(){
return hire;
}
public String toString(){
return "I am " + getname() + hire;
}
}