further concepts: inheritance

Like humans inherit attributes like eye color or hair color from their parents, classes in OOP can inherit attributes and methods from parent classes.

(different to biological inheritance we only have one parent and for that reason no mix of ancestor attributes e.g. mothers eyes were blue and fathers eyes were brown)

Why using inheritance

We can make use of this concept to re-use a given class and extend it to a new child or sub class with the same attributes and methods like the parent. And we can add new attributes and methods to the child.

without inheritance you just copy & paste code 1000 times

Let’s remember our transport box class. We could want to add a material to it and maybe a color attribute.

Without inheritance we obviously copy and paste the code and add the additional lines of code for the additional attributes, setters, getters etc.

class MaterialBox {
   constructor (width, length, height, weight, material, color) {
     this._width    = width;
     this._length   = length;
     this._height   = height;
     this._weight   = weight;
     this._material = material;
     this._color    = color;
   }
   get width () {
       return this._width;
   }
   set width (width) {
       this._width = width;
   }
   get length () {
       return this._length;
   }
   set length(length) {
       this._length = length;
   }
   get height () {
       return this._height;
   }
   set height(height) {
       this._height = height;
   }
   get material () {
       return this._material;
   }
   set material(material) {
       this._material = material;
   }
   get color () {
       return this._color;
   }
   set color(color) {
       this._color = color;
   }
   get volume() {
      return this._width * this._length * this._height;
   }
 }
var birthdayPresent = new Box(20,35,15,0.2,'paper','red');
console.log(birthdayPresent);

inheritance is more elegant

You can tell a new class to be a child or sub class of some other one by using the extends keyword. The MaterialBox as a child of Box would then look like this:

class MaterialBox extends Box {
   constructor (width, length, height, weight, 
                material, color) {
     super(width, length, height, weight)
     this._material = material;
     this._color    = color;
   }
   get material () {
       return this._material;
   }
   set material(material) {
       this._material = material;
   }
   get color () {
       return this._color;
   }
   set color(color) {
       this._color = color;
   }
 }

Before extending the class definition of Box class needs to be evaluated before.

Have you recognized the reserved word super()? This is the way how the constructor of the parent class has to be called. The Box classes constructor had 4 parameters, so we need to pass 4 parameters to the super() method too.