• abstract 抽象类


    抽象类

    abstract 用于定义抽象类和其中的抽象方法。

    什么是抽象类?

    首先,抽象类是不允许被实例化的:

    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'.

    上面的例子中,我们定义了一个抽象类 Animal,并且定义了一个抽象方法 sayHi。在实例化抽象类的时候报错了。

    其次,抽象类中的抽象方法必须被子类实现:

    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'.

    上面的例子中,我们定义了一个类 Cat 继承了抽象类 Animal,但是没有实现抽象方法 sayHi,所以编译报错了。

    下面是一个正确使用抽象类的例子:

    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');

    上面的例子中,我们实现了抽象方法 sayHi,编译通过了。

    需要注意的是,即使是抽象方法,TypeScript 的编译结果中,仍然会存在这个类,上面的代码的编译结果是:

    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');
  • 相关阅读:
    简单 dp 题选做
    UVa11327
    Codeforces Round #641 (div.2) 题解
    新博客
    数位dp的学习
    stl粗略用法
    cf437C The Child and Toy
    poj1995 Raising Modulo Numbers
    Tarjan的学习
    最短路模板
  • 原文地址:https://www.cnblogs.com/flxy-1028/p/10959722.html
Copyright © 2020-2023  润新知