Subclass constructor

I created a superclass (Person) and 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 am getting error: link name cannor and date of birth before calling supertype cosntructor. I tried:

public Student(){
    super()
}

      

but my cursor says that I should use super(name, birthdate);

+3


source to share


4 answers


If your default constructor for Student

must use a two-argument constructor Person

, you will need 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

do not appear in subclasses as they are declared private

.

+4




You will need to create a Student constructor that accepts name and birthday as parameters.



The example you provided will not work unless this instance has been created.

+1


source


It looks like there are a few misconceptions here:

When you create Student

, there is no separate object Person

- there is only Student

one that has all the properties Person

.

The constructor is what Student creates, so there is no other Student / Person inside the constructor whose fields you could reference. Once you call super

, you have initialized part of the Person

object and the fields from Person

are available, but since this is a new object, they cannot be set to anything unless you do it in the constructor.

Your options: or

1) use the defaults set in Person

:

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

      

2) Take values ​​as parameters and pass them to the constructor Person

:

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

      

3) Specify new defaults:

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

      

+1


source


You need to get the name and parameters of the parent date somehow. What about:

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

      

you can also do:

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

      

0


source







All Articles