Java - 我的super.toString返回null

时间:2018-02-15 16:25:11

标签: java tostring super

我遇到的问题是我的部门中的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());

}
}

1 个答案:

答案 0 :(得分:0)

初看起来,在我看来,Department构造函数调用带有参数Teacher的Teacher构造函数。

在这个构造函数中,super()没有被调用,也没有编译,所以我猜你在复制粘贴期间可能遗漏了一些东西。

无论如何,我担心这是一个非常低效的代码,因为你从数组开始重新创建了Teacher对象,最重要的是,你丢失了部分信息。