School Catalouge Project

Hi,

I’m having problems understanding inheritance and the use of ‘constructor’ definition when extending classes. For example, in the ‘School Catalouge’ project I wrote the following …

class School {
  constructor(name, numberOfStudents) {
    this._name = name;
    this._numberOfStudents = numberOfStudents;
    this._level = level;  
  }

and…

class Primary extends School {
  constructor(name, numberOfStudents, pickupPolicy) {
    super(name);
    this._numberOfStudents = numberOfStudents;
    this._pickupPolicy = pickupPolicy;
  }
  get pickupPolicy() {
    return this._pickupPolicy;
  }
}

which worked ok. What I don’t understand is why you only need to make a ‘super’ reference to the first variable in the Parent Class definition? When first building the Constructor, I wrote…

class Primary extends School {
  constructor(name, numberOfStudents, pickupPolicy) {
    super(name);
    super(numberOfStudents);
    this._pickupPolicy = pickupPolicy;
  }
  get pickupPolicy() {
    return this._pickupPolicy;
  }
}

which gave a reference error. Is it always the case that you only need to make a single ‘super’ reference to the first variable in a Parent Class constructor definition? :thinking:

Thanks :slightly_smiling_face:

1 Like

Hi there, welcome to the community!

As I understand it, the super() method is what invokes the constructor for the parent class. You only need to call the constructor once in order to create the instance of that class.

By calling super() twice, you’re attempting to create the instance of the object twice for the same object… which is kinda wrong.

Rather, if you need to initialise properties from the parent class, you call super() once with all the properties you need to initialise:

class Primary extends School {
    constructor(name, numberOfStudents, pickupPolicy) {
        super(name, numberOfStudents);
...

Doing so, super() calls the parent class constructor with the correct number of parameters to initialise the properties which are inherited from the parent - name and numberOfStudents in this case.

Does that make sense? :slight_smile:

Many thanks. :slightly_smiling_face: Yes, that makes sense. I hadn’t seen the…

super(variable1, variable2);

notation before. I was thinking of the super(x) defnition as a hook to the parent class. Thanks for the clarification.

1 Like

That’s not wrong, really - super() is used to deal with the stuff which the class you’re trying to instantiate gets from the parent. All you missed was initialising multiple parent properties. :slight_smile: