2012-03-15 71 views
3

我创建了一个超类(人)&一个子类(学生)子类的构造

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) 
} 

我得到的错误:cannor引用名超cosntructor之前&生日已调用。 我想:

public Student(){ 
    super() 
} 

,但我当然仪说,我应该使用super(name, birthdate);

回答

1

你需要创建一个学生构造函数的名字和生日作为参数。

除非学生已经实例化,否则您提供的示例将不起作用。

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

+0

我已经有2参数构造函数。 事情是我必须使用超级(名称,出生日期)在0参数构造函数 – user1200325 2012-03-15 04:54:56

+0

@ user1200325 - 我修改了我的答案 – 2012-03-15 05:04:53

0

您需要以某种方式获取学生的姓名和出生日期参数。如何:

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

你也可以这样做:

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

@Jochen - 复制粘贴 - 所有邪恶的根:) – MByD 2012-03-15 04:55:02

+0

我已经有2参数构造函数。 事情是我必须使用超(名称,出生日期)在0参数构造函数 – user1200325 2012-03-15 04:56:31

+0

请参阅编辑。 – MByD 2012-03-15 05:01:13

1

貌似有一些误解的位置:

当您创建Student,没有一个单独的Person object--只有Student它具有Person的所有属性。

构造函数是什么构建学生,所以在构造函数中没有其他学生/人员的字段,你可以参考。一旦你调用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)); 
}