【发布时间】:2018-02-15 16:25:10
【问题描述】:
我在 Department 中的 toString 方法返回空值时遇到问题,似乎 super.toString 没有获取输入的值。我不确定代码哪里出错了,我知道要整理很多,我试图摆脱任何不重要的代码。谢谢参观。抱歉,如果我的结构有误。
public class Person {
String name;
private int age;
private String ssn;
private boolean alive;
public Person(String name, int age, String ssn, boolean alive) {
this.name = name;
this.age = age;
this.ssn = ssn;
this.alive = alive;
}
public String toString() {
return "Name: " + this.getName() + "\n" +
"Age: " + this.getAge() + "\n" +
"SSN: " + this.getSsn() + '\n' +
"Alive: " + this.isAlive();
}
}
教师扩展人
public class Teacher extends Person {
private String id;
private int salary;
private int num_yr_prof;
public Teacher(String name, int age, String ssn, boolean alive, String id, int salary, int num_yr_prof) {
super(name, age, ssn, alive);
this.id = id;
this.salary = salary;
this.num_yr_prof = num_yr_prof;
}
public Teacher(Teacher t) {
this.id = t.id;
this.salary = t.salary;
this.num_yr_prof = t.num_yr_prof;
}
@Override
public String toString() {
return super.toString() +
"\nID: " + getId() +
"\nSalary: $" + getSalary() +
"\nYears as a prof: " + getNum_yr_prof();
}
}
这个类使用一组教师
public class Department {
private String deptName;
private int numMajors;
private Teacher[] listTeachers;
public Department(String dN, int nM, Teacher[] lT) {
this.deptName = dN;
this.numMajors = nM;
this.listTeachers = new Teacher[lT.length];
for (int i = 0; i <lT.length ; i++) {
listTeachers[i] = new Teacher(lT[i]);
}
}
public String toString() {
String output = "Department: ";
output += "\n Name: " + getDeptName();
output += "\n Majors: " + getNumMajors();
output += "\n Teachers: \n";
for (int i = 0; i < listTeachers.length; i++) {
output += listTeachers[i].toString(); //This is returning null values
}
return output;
}
}
主要方法
public class lab4prt2 {
public static void main(String[] args) {
Teacher[] teachers = new Teacher[]{
new Teacher(
"Tracy",
36,
"39890280",
true,
"4859279",
100000,
5)
};
Department d1 = new Department("Math", 4, teachers);
System.out.println(d1.toString());
}
}
【问题讨论】:
-
此代码无法编译。
Teacher(Teacher t)构造函数不会调用超级构造函数,或者它会(隐式)调用并且您没有在Person中显示无参数构造函数。 -
在这种情况下,那个无参数构造函数是做什么的?我猜它不会初始化它的任何实例字段。