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() );