Java - 超级参考

时间:2014-02-23 01:00:47

标签: java super

所以我想为另一个类的子类添加一个toString()方法。如何在其中添加super以合并超类已经完成的事情? 在我的代码中,您可以看到我有一个Person,其中包含多个私有变量,名称,性别和年龄。如何将类Person中使用的toString方法用于类Teacher的toString方法?感谢

这是我的代码:

class Person {

protected String myName; // name of the person
protected int myAge; // person's age
protected String myGender; // "M" for male, "F" for female
// constructor

public Person(String name, int age, String gender) {
    myName = name;
    myAge = age;
    myGender = gender;
}

public String getName() {
    return myName;
}

public int getAge() {
    return myAge;
}

public String getGender() {
    return myGender;
}

public void setName(String name) {
    myName = name;
}

public void setAge(int age) {
    myAge = age;
}

public void setGender(String gender) {
    myGender = gender;
}

@Override
public String toString() {
    return myName + ", age: " + myAge + ", gender: " + myGender;

}
}


class Teacher extends Person {

protected String mySubject; // Student Id Number
protected double mySalary; // grade point average
// constructor

public Teacher(String name, int age, String gender,
        String subject, double salary) {
// use the super class' constructor
    super(name, age, gender);
// initialize what's new to Student
    mySubject = subject;
    mySalary = salary;
}

public String getSubject() {
    return mySubject;
}
public double getSalary() {
    return mySalary;
}
public void setSubject(String subject) {
    mySubject = subject;

}
public void setSalary(double salary) {
    mySalary = salary;
}
@Override
public String toString() {

}

1 个答案:

答案 0 :(得分:2)

在教师

中添加对super.toString()的调用
public String toString()
{
   return super.toString()
}