对象的数据域的值,为了保证封装性,一般设置为私有的数据域,然后通过共有的访问器和更改器进行更改。然而,当一个访问器返回引用可变对象,就会出现错误,破坏其封装性。举例子如下
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;
}
}
结果如下
I am duanWed Jun 06 02:02:38 CST 2018
I am error!Wed Jun 06 02:02:38 CST 2018
I am error!Tue May 15 22:26:11 CST 2018
我们发现,本来对象的hire Date我们是不希望变的,然而因为Date本身可以修改,就出现了这样的问题。这个时候,应该在返回的值改为其实例域的副本,就解决了这个问题。该后代码如下:
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 (Date) hire.clone();
}
public String toString(){
return "I am " + getname() + hire;
}
}
结果如下:
I am duanWed Jun 06 02:07:42 CST 2018
I am error!Wed Jun 06 02:07:42 CST 2018
I am error!Wed Jun 06 02:07:42 CST 2018
我们发现达到了目的。另外注意LocalDate本身就是不可变的,所以也可以实现这一点。代码如下
package chapter4;
import java.time.LocalDate;
public class TestEmployee {
public static void main(String[] args) {
Employee[] staff = new Employee[2];
staff[0] = new Employee("duan ",LocalDate.now());
staff[1] = new Employee("error!",LocalDate.now());
System.out.println(staff[0]);
System.out.println(staff[1]);
staff[1].getdate().minusDays(100);
System.out.println(staff[1].getdate().minusDays(100));
System.out.println(staff[1]);
}
}
class Employee{
private String name;
private LocalDate hire;
Employee(String name,LocalDate hire){
this.name = name;
this.hire = hire;
}
public String getname(){
return name;
}
public LocalDate getdate(){
return hire;
}
public String toString(){
return "I am " + getname() + hire;
}
}
结果如下
I am duan 2018-06-06
I am error!2018-06-06
2018-02-26
I am error!2018-06-06
文章最后说一个可能出现的小错误,在对象数据域声明的变量,就不要在其方法中重新声明,这样会使得这个引用只能在其方法中起作用。正确的方法是直接使用就好。