Melky
Melky

Reputation: 167

Trouble with inner class, toString confliction

Based on one of the Head First books examples I'm having a little trouble in which the toString method is causing issues with my student and they're uni and home address being outputted correctly. All i'm trying to do is output if a students uni address is empty use his home address else use the uni one.

But my test data looks like the following

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

Other Class

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";
    }
}

}

Upvotes: 0

Views: 549

Answers (1)

Kevin DiTraglia
Kevin DiTraglia

Reputation: 26078

Your getHomeAddress method takes care of displaying the uni address, so this line:

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

can be shortened to:

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

Otherwise your getHomeAddress method will pull the uni address, then your getUniAddress method will pull the uni address again.

Also in your address toString you are pulling the person's name and you probably didn't mean to (and you might not want a newline here either since you have a newline in your other toString method).

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

Upvotes: 3

Related Questions