⊗jsOpIhCn 33 of 60 menu

Constructor in Inheritance in OOP in JavaScript

When inheriting, you can override the parent's constructor. Let's look at an example. Let's say we have the following parent class:

class User { constructor(name, surn) { this.name = name; this.surn = surn; } getName() { return this.name; } getSurn() { return this.surn; } }

Let the following class inherit from the parent class:

class Student extends User { }

Let's say we want to extend the constructor in the descendant class by adding additional parameters to it:

class Student extends User { constructor(name, surn, year) { } }

In this case, we definitely need to call the parent's constructor via super as the first line:

class Student extends User { constructor(name, surn, year) { super(); } }

The super command is essentially a parent constructor. Therefore, we will pass the required parameters to it:

class Student extends User { constructor(name, surn, year) { super(name, surn); } }

Now in the descendant we will write the year of study in our descendant property:

class Student extends User { constructor(name, surn, year) { super(name, surn); this.year = year; } }

Let's make a getter for the year of study:

class Student extends User { constructor(name, surn, year) { super(name, surn); this.year = year; } getYear() { return this.year; } }

Let the Employee class inherit from the User class from this lesson.

Override the parent's constructor in the Employee class, adding a parameter with age and salary.

Make getters for age and salary.

msuzcswenes