子类构造函数

时间:2012-03-15 04:48:47

标签: java constructor subclass

我创建了一个超类(Person)&子类(学生)

public class Person{
private String name;
private Date birthdate;
//0-arg constructor
public Person() {
    birthdate = new Date("January", 1, 1000);
    name = "unknown name";
}
//2-arg constructor
public Person(String newName, Date newBirthdate){
    this.name = newName;
    this.birthdate = newBirthdate;
}

//Subclass
public class Student extends Person{

    public Student(){
        super(name, birthdate)
}

我收到错误:插件参考名称&在supertype cosntructor被调用之前的birthdate。 我试过了:

public Student(){
    super()
}

但我的课程测试员说我应该使用super(name, birthdate);

4 个答案:

答案 0 :(得分:4)

如果Student的默认构造函数需要使用Person的双参数构造函数,则必须像这样定义子类:

public class Student extends Person{

    public Student() {
        super("unknown name", "new Date("January", 1, 1000));
    }

    public Student(String name, Date birthdate) {
        super(name, birthdate);
    }
}

另请注意,Person.namePerson.birthdate在子类中不可见,因为它们已声明为private

答案 1 :(得分:1)

您需要创建一个以名称和生日为参数的学生构造函数。

除非学生已经实例化,否则您提供的示例将无效。

答案 2 :(得分:1)

看起来这里有一些误解:

创建Student时,没有单独的Person对象 - 只有Student具有Person的所有属性。

构造函数是构建 Student的内容,因此在构造函数中没有其他可以引用其字段的学生/人员。致电super后,您已初始化对象的Person部分,并且可以访问Person中的字段,但由于它是新对象,因此无法将其设置为除非你在构造函数中执行任何操作。

您的选择是:

1)使用Person中设置的默认值:

public Student() {
   super(); // this line can be omitted as it's done by default
}

2)将值作为参数并将它们传递给Person构造函数:

public Student(String newName, Date newBirthdate) {
    super(newName, newBirthdate);
}

3)提供新的默认值:

public Student() {
    super("Bob", new Date("January", 1, 1990));
}

答案 3 :(得分:0)

您需要以某种方式获取学生的姓名和生日参数。怎么样:

public Student(String name, Date birthdate){
    super(name, birthdate)
}

你也可以这样做:

public Student(){
    super("unknown name", new Date("January", 1, 1000));
}
相关问题