The following snippet shows how to write an abstract class and method.

Goals

  • The abstract class cannot be instantiated;
  • The abstract method must be implemented.
/**
 * Abstract Class Fruit.
 */
class Fruit {
  constructor() {
    if (this.constructor === Fruit) {
      throw new Error('Class "Fruit" cannot be instantiated')
    }
    this.color = 'unknown'
  }

  someMethod() {
    throw new Error('Method "someMethod()" must be implemented.')
  }
}

//const fruit = new Fruit() <-- ERROR

/**
 * Concrete  Class Fruit.
 */
class Orange extends Fruit {
  constructor() {
    super()
    this.color = 'orange'
  }
  someMethod() {
    console.log('Hello someMethod():', this.color)
  }
}

const orange = new Orange()
orange.someMethod()

See example online at https://codesandbox.io/s/abstract-class-and-method-clvze


Did you find it interesting? Follow me on Twitter.

Categories: snippet

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *