我很困惑为什么我的程序按特定顺序打印语句?
我有一个Student class
,里面是一个Inner Class of Address
。该程序的想法是首先为学生对象分配一个家庭地址,然后利用内部地址类分配一个大学/学期时间地址。
代码如下:
学生班(有内部地址班)
public class Student {
private String name;
private Address homeAddress, uniAddress;
public Student(String name, int houseNumber, String homeStreet) {
this.name = name;
homeAddress = new Address(houseNumber, homeStreet);
}
public String getName() {
return name;
}
public Address getHomeAddress() {
String s = "n/a";
if (homeAddress != null) {
return homeAddress;
} else {
// System.out.println(s);
return null;
}
}
public void setUniAddress(int num, String add) {
uniAddress = new Address(num, add);
}
public Address getUniAddress() {
String s = "n/aa";
//If uniAddress isn't set,
// then "n/aa" gets printed before anything else i/e toString() method - WHY?
if (uniAddress == null) {
System.out.println(s);
return null;
} else {
return uniAddress;
}
}
@Override
public String toString() {
return "NAME: " + getName() + "\n"
+ "HOME ADDRESS: " + getHomeAddress() + "\n"
+ "TERM TIME ADDRESS: " + getUniAddress();
}
// Inner Class
public class Address {
private int number;
private String street;
public Address(int no, String street) {
number = no;
this.street = street;
}
@Override
public String toString() {
//return name + "\n" + number + " " + street;
return number + " " + street;
}
}
} // more Student methods .. }
TestStudent 类(使用 main 方法)
public class TestStudent {
public static void main(String[] args) {
//Home Address
Student s1 = new Student("Cathy", 21, "Smithfield Drive");
//Uni Address
s1.setUniAddress(72, "Nottingham Drive");
Student.Address anotherAddress = s1.new Address(8, "Deerfield Way");
// note the use of new
System.out.println(s1.toString());
}
}
输出是:
n/aa
NAME: Cathy
HOME ADDRESS: 21 Smithfield Drive
TERM TIME ADDRESS: null
(all on new lines)
如果我没有为学生分配 Uni 地址(即,如果我在 main 方法中注释掉适当的行 - 调用该setUniAddress()
方法),那么我很好奇为什么 getUniAddress() 方法中的'n/aa'是打印前的toString()
方法吗?(如上)
如果我调用 setUniAddress() 方法,输出是:
NAME: Cathy
HOME ADDRESS: 21 Smithfield Drive
TERM TIME ADDRESS: 72 Nottingham Drive
(all on new lines)
这似乎按预期工作。
我也想知道如何,而不是打印 'null' 到TERM TIME ADDRESS :(当setUniAddress()
方法未被调用时),我可以在它的位置返回 'n/aa' - 这就是我试图做的?
谢谢。