我有这样的构造函数

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


我该怎么办?

最佳答案

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


您可能要检出Guava's Strings的isNullOrEmpty(),例如(如riccardo.cardin所指出的,只有一个return是更好的做法):

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

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

    return nameString;
}

09-10 23:09