最近看java书时,上面有提到 “可变对象访问器” 不理解,看了下代码,于是就自己敲了一遍,理解为:
可变对象访问器:在类A中定义类B做其属性时,直接用get方法返回此属性,那得到的是其引用,然后接收此返回值的对象(类B的一个对象)将可以改变类A对象的属性B的值。
解决的方法就是:在类A中返回此对象属性的克隆(clone),而不是直接返回此对象属性。
详细代码如下:
- public class Employee {
- public Employee(String n,double s,int year,int month,int day){
- name = n;
- salary = s;
- GregorianCalendar calendar = new GregorianCalendar(year,month-1,day);
- hireDay = calendar.getTime();
- }
-
- public Date getHireDay(){
- return hireDay;
- }
-
- private String name;
- private double salary;
- private Date hireDay;
- public static void main(String args[]){
- Employee harry = new Employee("harry",1000.0,2012,6,12);
- Date d = harry.getHireDay();
- System.out.println("d: "+d);
- System.out.println("harry.getHireDay(): "+harry.getHireDay());
- double tenYearsInMilliSeconds = 10*365.25*23*60*60*1000;
- d.setTime(d.getTime() - (long)tenYearsInMilliSeconds);
- System.out.println("d: "+d);
- System.out.println("harry.getHireDay(): "+harry.getHireDay());
- }
运行后的结果:
- d: Tue Jun 12 00:00:00 CST 2012
- harry.getHireDay(): Tue Jun 12 00:00:00 CST 2012
- d: Mon Nov 11 16:30:00 CST 2002
- harry.getHireDay(): Mon Nov 11 16:30:00 CST 2002
修改后的代码:
将返回可变对象的引用的clone
- public Date getHireDay(){
- return (Date)hireDay.clone();
- }
修改后的结果:
- d: Tue Jun 12 00:00:00 CST 2012
- harry.getHireDay(): Tue Jun 12 00:00:00 CST 2012
- d: Mon Nov 11 16:30:00 CST 2002
- harry.getHireDay(): Tue Jun 12 00:00:00 CST 2012
阅读(2051) | 评论(0) | 转发(1) |