Reputation: 31
I created a superclass (Person) & a subclass (Student)
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)
}
I get the error: cannor reference name & birthdate before supertype cosntructor has been called. I tried:
public Student(){
super()
}
but my course tester says I should use super(name, birthdate);
Upvotes: 3
Views: 250
Reputation: 27926
Looks like there are a few misconceptions here:
When you create Student
, there isn't a separate Person
object--there's just a Student
which has all the properties of a Person
.
The constructor is what builds the Student, so inside the constructor there is no other Student/Person whose fields you could reference. Once you call super
you've initialized the Person
portion of the object, and the fields from the Person
are accessible, but since it's a new object they can't have been set to anything unless you do it in the constructor.
Your options are either to :
1) use the defaults as set up in Person
:
public Student() {
super(); // this line can be omitted as it's done by default
}
2) Take values as parameters and pass them to the Person
constructor:
public Student(String newName, Date newBirthdate) {
super(newName, newBirthdate);
}
3) Provide new defaults:
public Student() {
super("Bob", new Date("January", 1, 1990));
}
Upvotes: 1
Reputation: 234867
If your default constructor for Student
needs to use the two-argument constructor of Person
, you'll have to define your subclass like this:
public class Student extends Person{
public Student() {
super("unknown name", "new Date("January", 1, 1000));
}
public Student(String name, Date birthdate) {
super(name, birthdate);
}
}
Note also that Person.name
and Person.birthdate
are not visible in subclasses because they are declared private
.
Upvotes: 4
Reputation: 137442
You need to get the name and birthdate parameters for student somehow. How about:
public Student(String name, Date birthdate){
super(name, birthdate)
}
you can also do:
public Student(){
super("unknown name", new Date("January", 1, 1000));
}
Upvotes: 0
Reputation: 22692
You'll need to create a Student constructor that takes the name and birthday as parameters.
The example you've provided won't work unless the Student is already instantiated.
Upvotes: 1