public class Person
{
private String name;
private Date born;
private Date died;//null indicates still alive. public Person(String initialName, Date birthDate, Date deathDate)
{
if (consistent(birthDate, deathDate))
{
name = initialName;
born = new Date(birthDate);//书上为啥要这么写?如果写成born = birthDate;也对啊
if (deathDate == null)
died = null;
else
died = new Date(deathDate);
}
else
{
System.out.println("Inconsistent dates. Aborting.");
System.exit(0);
}
} }
{
private String name;
private Date born;
private Date died;//null indicates still alive. public Person(String initialName, Date birthDate, Date deathDate)
{
if (consistent(birthDate, deathDate))
{
name = initialName;
born = new Date(birthDate);//书上为啥要这么写?如果写成born = birthDate;也对啊
if (deathDate == null)
died = null;
else
died = new Date(deathDate);
}
else
{
System.out.println("Inconsistent dates. Aborting.");
System.exit(0);
}
} }
否则,比如有一个 Date birthDate对象,创建两个Person对象:
Person p1 = new Person(..,birthDate,..);
Person p2 = new Person(..,birthDate,..);
他们共享birthDate可能会出问题。
你的意思是如果P2将BIRTHDAY修改了以后,P1会受到影响?
下列情况:
Date birthDate = new Date("1987/01/01");
用birthDate新建两个Persion:
Person p1 = new Person(..,birthDate,..);
Person p2 = new Person(..,birthDate,..);你出生之后生日是不可修改的吧。如果你修改了birthDate引用所指向的对象的属性比如:birthDate.setYear(2010)// 如果有这个方法的话, 那p1,p2的birthDate不是都变了?
如果接受一个对象类型的变量,都是new一个对象出来,然后值相等。如果直接用把引用指向传进来的那个值的地址的话,那么在你NEW这个Person的地方的参数生日,和这个对象里面的生日,两个生日指向的是同一个内存地址。如果其中一个发生了改变,比如格式化日期格式。那么另一个使用的值也就都发生了变化。所以不能直接用引用去接受传进来的参数。不过话说,字符串也是“引用传递”(这个说法不正确,暂且这么认为),不知道为什么Name不是New一个出来去接受,应该是在本题中NAME是肯定不会改变也不会有Format,自始自终都不会改变,或者只在传递的时候用到后面就没有在用到那个参数,所以Name就直接等于了。楼主看下,在调用Persong之后,那个日期参数是不是还有别的用处。或者这个方法里,日期发生过了任何格式上的变化。
public Date getDate(){
return (Date)birthDate.clone();
}