woshiwwq 2016-01-12 02:56 采纳率: 0%
浏览 1614

java可变类和不可变类区别中,对于不可变类克隆的问题

import java.util.Date;                                          
public final class BrokenPerson                                
{                                                              
  private String firstName;                                    
  private String lastName;                                     
  private Date dob;                                            

  public BrokenPerson( String firstName,                   public BetterPerson( String firstName, 
    String lastName, Date dob)                                             String lastName, Date dob)          
  {                                                                                      {                                     
   this.firstName = firstName;                                             this.firstName = firstName;         
   this.lastName = lastName;                                             this.lastName = lastName;           
   this.dob = dob;     //error               this.dob = new Date( dob.getTime() ); //correct 
  }                                                                                       }                                      

  public String getFirstName() 
  { 
   return this.firstName; 
  } 
  public String getLastName() 
  { 
   return this.lastName; 
  } 
  public Date getDOB()                                               public Date getDOB()                     
  {                                                                                    {                                      
   return this.dob;    //error                  return new Date( this.dob.getTime() );//correct 
  }                                                                                     }                                      
} 

上面的代码是在别人的博客上看到的,我能够理解在get一个Date类型的时候进行克隆,但是我不能理解在构造方法中的Date类型为什么还需要进行克隆之后才赋值给成员变量,也就是这句:this.dob = new Date( dob.getTime() );

  • 写回答

4条回答 默认 最新

  • haopeiren 2016-01-12 03:14
    关注

    我也是个菜鸟,不过大概也能猜到。如果你外部调用getDate之后,对获得的那个对象更改了,那么BrokenPerson里面的属性也就更改了,那就跟final不符了。
    所以在getDate的时候才创建了这个对象的一个副本

    评论

报告相同问题?