zoukankan      html  css  js  c++  java
  • [TypeScript] Inheritance

    Inheritance is a way to
    indicate that a class receives behavior from a parent class. Then we can override, modify or augment
    those behaviors on the new class.

     1  class Report {
     2     data: Array<string>;
     3 
     4    constructor(data: Array<string>) {
     5      this.data = data;
     6    }
     7 
     8    run() {
     9      this.data.forEach(function(line) { console.log(line); });
    10    }
    11  }

    Call the class:

    var r: Report = new Report(['First line', 'Second line']);
    r.run();

     Result:

     First line
     Second line

    Now let’s say we want to have a second report that takes some headers and some data but we still
    want to reuse how the Report class presents the data to the user.
    To reuse that behavior from the Report class we can use inheritance with the extends keyword:

     class TabbedReport extends Report {
         headers: Array<string>;
    
        constructor(headers: string[], values: string[]) {
           this.headers = headers;
           super(values)  // In Report class : data
        }
    
       run() {
       console.log(headers);
         super.run();
       }
     }

    Run:

    var headers: string[] = ['Name'];
    var data: string[] = ['Alice Green', 'Paul Pfifer', 'Louis Blakenship'];
    var r: TabbedReport = new TabbedReport(headers, data)
    r.run();
  • 相关阅读:
    [HNOI2006]超级英雄
    [CTSC1999]家园
    火星探险问题
    [HNOI2008]GT考试
    [USACO14DEC]后卫马克Guard Mark
    [NOI2018]归程
    [USACO15DEC]最大流Max Flow
    [NOIPlus]斗地主
    [LUOGU] P3128 [USACO15DEC]最大流Max Flow
    [BZOJ] 1878: [SDOI2009]HH的项链
  • 原文地址:https://www.cnblogs.com/Answer1215/p/4929127.html
Copyright © 2011-2022 走看看