内部类的麻烦,toString冲突

时间:2012-11-09 17:44:07

标签: java tostring inner-classes

基于Head First书籍的一个例子,我遇到了一些麻烦,其中toString方法导致了我的学生问题,他们是单身和家庭地址正确输出。所有我想要做的就是输出如果学生的uni地址是空的,请使用他的家庭地址,否则使用uni。

但我的测试数据如下所示

  

John John72 Nottingham Drive

     

John72 Nottingham Drive

public class Test {
public static void main(String[] args){
    Student student1 = new Student("John", 19, "Walkers Way");
    student1.setUniAddress(72, "Nottingham Drive");
    System.out.print(student1.toString());
    }
}

其他班级

public class Student {
private String name;
private Address homeAddress, uniAddress;

public Student(String name, int houseNumber, String homeStreet){
    this.name = name;
    this.homeAddress = new Address(houseNumber, homeStreet);
}



public String getName() { return this.name; }
public Address getHomeAddress(){
    if(this.uniAddress == null){
        return this.homeAddress;
    }else{
        return getUniAddress();//this.uniAddress;
    }
}

public Address getUniAddress() { return this.uniAddress; }
public void setUniAddress(int number, String add){
    Address address = new Address(number, add);
    uniAddress = address;
}

@Override
public String toString(){
    return getName() + " " + getHomeAddress() + " " + getUniAddress() + "\n";
}

public class Address{
    private int number;
    private String street;
    public Address(int no, String street){
        this.number = no;
        this.street = street;
    }

    @Override
    public String toString(){
        return name + number + " " + street + "\n";
    }
}

}

1 个答案:

答案 0 :(得分:3)

你的getHomeAddress方法负责显示uni地址,所以这一行:

return getName() + " " + getHomeAddress() + " " + getUniAddress() + "\n";

可缩短为:

return getName() + " " + getHomeAddress() + " " + "\n";

否则,您的getHomeAddress方法将提取uni地址,然后您的getUniAddress方法将再次提取uni地址。

同样在您的地址toString中,您正在提取此人的姓名而您可能并不是故意的(因为您在其他toString方法中有换行符,因此您可能不需要新行。 )。

@Override
public String toString(){
    return number + " " + street;
}