Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subclass constructor

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

like image 366
user1200325 Avatar asked Jun 19 '26 01:06

user1200325


1 Answers

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.

like image 180
Ted Hopp Avatar answered Jun 20 '26 14:06

Ted Hopp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!