abstract abstract class

Abstract class

abstract for defining abstract classes and abstract methods therein.

What is an abstract class?

First, the abstract class is allowed to be instantiated:

abstract class Animal {
  public name;
  public constructor(name) {
    this.name = name;
  }
  public abstract sayHi();
}
 
let a = new Animal('Jack');
 
// index.ts(9,11): error TS2511: Cannot create an instance of the abstract class 'Animal'.

 

In the above example, we define an abstract class Animal, and defines an abstract method sayHi. In the example of time given the abstract class.

Secondly, abstract methods abstract class must implement subclasses:

abstract class Animal {
  public name;
  public constructor(name) {
    this.name = name;
  }
  public abstract sayHi();
}
 
class Cat extends Animal {
  public eat() {
    console.log(`${this.name} is eating.`);
  }
}
 
let cat = new Cat('Tom');
 
// index.ts(9,7): error TS2515: Non-abstract class 'Cat' does not implement inherited abstract member 'sayHi' from class 'Animal'.

 

In the above example, we define a class Cat inherits the abstract class Animal, but does not implement abstract methods sayHi, so the compiler being given.

The following is an example of proper use of the abstract class:

abstract class Animal {
  public name;
  public constructor(name) {
    this.name = name;
  }
  public abstract sayHi();
}
 
class Cat extends Animal {
  public sayHi() {
    console.log(`Meow, My name is ${this.name}`);
  }
}
 
let cat = new Cat('Tom');

 

In the above example, we implemented the abstract methods sayHi, by the compiler.

Note that, even if the method is abstract, compile the results of TypeScript, there would still be this class, compiled the results of the above code is:

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Animal = (function () {
    function Animal(name) {
        this.name = name;
    }
    return Animal;
}());
var Cat = (function (_super) {
    __extends(Cat, _super);
    function Cat() {
        _super.apply(this, arguments);
    }
    Cat.prototype.sayHi = function () {
        console.log('Meow, My name is ' + this.name);
    };
    return Cat;
}(Animal));
var cat = new Cat('Tom');

 

Guess you like

Origin www.cnblogs.com/flxy-1028/p/10959722.html