“This is the sixth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

preface

In the previous article, we introduced classes and modifiers in TS. In this article, we continue to look at two things related to classes in TS: class inheritance and abstract classes

Class inheritance

We know that js has inheritance. Js used functions to simulate classes until ES6 introduced the use of class and extends keywords. So why inheritance? In fact, the benefit of inheritance is that you can reuse your code better and maintain it better later

Inheritance in TS class inheritance in ES6 is very familiar. Subclasses can extend a class using the extends keyword for example:

class Person{
  name:string;
  age:number;
  constructor(name,age){
    this.name = name;
    this.age = age; }}class student extends Person{
  score:number;
  constructor(name,age,score){
    super(a);this.score = score; }}Copy the code

As you can see, as in ES6, the subclass constructor must be added with super() to perform the parent class’s constructor function

So it’s often said that an instance of a subclass is also an instance of a superclass

Inherited format:

class A {}
class B extends A {
  constructor() {
    super();
  }
}
Copy the code

As above, if B inherits A, B is called A superclass, and A is called A subclass. Instances of subclasses are public and protected properties and methods that can inherit from their superclass

In addition to inheritance, there is another feature of object orientation: polymorphism is actually quite common in polymorphic JS and TS, which can be interpreted as multiple states, such as which function to execute at runtime

An abstract class

Abstract means non-concrete, so an abstract class is a non-concrete class. So abstract classes have no function on their own, and are usually used as superclasses

Define an abstract class using the abstract class keyword

abstract class A{
  abstract fn():number;
}
Copy the code

An abstract class specifies that all non-abstract subclasses that inherit from it must implement specified functions and operations, or an error will be reported

class B extends A{
  constructor(){
    super(a); } fn():number{
    return 1}}Copy the code

Note that abstract classes are only base classes and cannot be new

let b = new B();/ / can
let a = new A();/ / an error
Copy the code