Jump to content

JavaScript/OOP-classes/Exercises

From Wikibooks, open books for an open world

Topic: OOP - 2




1. Create a class 'Car' with (minimum) two properties.

Click to see solution
"use strict";

class Car {

  constructor(brand, model) {
    this.brand = brand;
    this.model = model;
  }
  show() {
    return "My car is a " + this.brand + " " + this.model;
  }
}

const myCityCar = new Car("Fiat", "Cinquecento");
const mySportsCar = new Car("Maserati", "MC20");

alert(myCityCar.show());
alert(mySportsCar.show());

2. Create a class 'Truck' that is a sub-class of the above 'Car' class. It has an additional property 'maxLoad'.

Click to see solution
"use strict";

class Car { // same as above
  constructor(brand, model) {
    this.brand = brand;
    this.model = model;
  }
  show() {
    return "My car is a " + this.brand + " " + this.model;
  }
}
class Truck extends Car {
  constructor(brand, model, maxLoad) {
    super(brand, model);
    this.maxLoad = maxLoad;
  }
  show() {
    return "My truck is a " + this.brand + " " + this.model + 
           ". It transports up to " + this.maxLoad;
  }
}

const myTruck = new Truck("Caterpillar", "D350D", "25 tonne");

alert(myTruck.show());