java构造函数空对象

ht4b089n  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(446)

我第一次在这里问很抱歉如果问得不好

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

            if (deathDate == null)
            {
                 died = null; 
            }
            else
            {
                 died = new Date(deathDate);
            }
        }
        else
        {
            System.out.println("Inconsistent dates.Aborting.");
            System.exit(0);
        }
    }
}

我的书里有这个密码。它只是代码的一部分,不是完整的代码。我只复制了我要问的部分。我的问题是。我们不能把它移走吗 if (deathDate == null) . 如果是的话 null ,那么 diednull 不管怎样?

bnl4lu3b

bnl4lu3b1#

继续读。有一个 else 声明。您的建议是将其替换为:

if (deathDate == null) died = null;
else died = new Date(deathDate);

使用:

died = new Date(deathDate);

这是行不通的;可以归结为 new Date(null) 将引发nullpointerexception。
注:这是疯狂的代码。当前置条件失败(日期不一致)时,抛出异常。您不会将某些内容打印到标准err并退出整个vm。将最后两行替换为 throw new IllegalArgumentException("Death date cannot be before birth date. Death: " + death + " birth: " +birth); .

tjvv9vkg

tjvv9vkg2#

您也可以替换代码:

if (deathDate == null)
{
     died = null; 
}
else
{
     died = new Date(deathDate);
}

对此:

died = null;
if (deathDate != null)
{
    died = new Date(deathDate);
}

相关问题