如何检查用户使用的构造函数

时间:2015-03-26 20:20:40

标签: java string

我有像这样的构造函数

    public Name(String firstName, String lastName)
{
    setFirstName(firstName);
    setLastName(lastName);        
}

public Name(String firstName, String lastName, String middleName)
{
    setFirstName(firstName);
    setLastName(lastName);
    setMiddleName(middleName);
}

我想覆盖我的toString()方法,就像这样

    @Override
    public String toString()
    {
        if(no middle name)
        {return  getFirstName() + " " + getLastName();}
        else if(has a middle name)
        {return  getFirstName() + " " + getMiddleName() + " " + getLastName();}
    }

我该怎么办?

1 个答案:

答案 0 :(得分:2)

@Override
public String toString()
{
    if(middleName == null)
    {return  getFirstName() + " " + getLastName();}
    else
    {return  getFirstName() + " " + getMiddleName() + " " + getLastName();}
}

您可能需要查看Guava's Strings的isNullOrEmpty(),例如(并且只有一个return,正如riccardo.cardin指出的那样,是更好的做法):

@Override
public String toString()
{
    String nameString = null;

    if (Strings.isNullOrEmpty(middleName))
    {
        nameString = getFirstName() + " " + getLastName();
    }
    else
    {
        nameString = getFirstName() + " " + getMiddleName() + " " + getLastName();
    }

    return nameString;
}