zoukankan      html  css  js  c++  java
  • TS之静态属性、静态方法 & 抽象类、抽象方法

    1.静态属性&静态方法

    class Person {
      public name: string;    // 保护属性
      public age: number = 20;
    
      static sex: string = "男";
      constructor(name: string) {
        this.name = name;
      };
    
      run() {  // 实例方法
        console.log(`${this.name}在奔跑`);
      }
      work() {
        console.log(`${this.name}在工作`);
      }
    
      static print() {  //静态方法
        console.log('print方法');
    
        console.log('print方法' + this.age);  // 报错,静态方法里无法直接调用当前类属性(只能调用静态属性)this.age是undefined
        console.log('print方法' + this.sex);
    
      }
    }
    
    let p = new Person("张三")
    // 调用实例方法
    p.run();
    // 调用静态方法
    Person.print();

     2.多态 ——一个函数,在不同情况下表现出不同的状态,就称为多态

    包括两种情况:

    • 重载(overload):一个函数,根据传入的实参值不同,选择执行不同的逻辑
    • 重写(override):子对象中定义了和父对象中同名的方法,当使用这个方法时,使用的时子对象这个方法,而不会使用父对象中的方法

    以重写为例:

    class Animal {
      name: string;
    
      constructor(name: string) {
        this.name = name;
      }
    
      // 父类的方法
      eat() {
        console.log('吃的方法');
      }
    }
    
    class Dog extends Animal {
      constructor(name: string) {
        super(name);
      }
      // 字类改写
      eat() {
        return this.name + "吃肉"
      }
    }
    
    class Cat extends Animal {
      constructor(name: string) {
        super(name)
      }
      // 字类改写
      eat() {
        return this.name + "吃鱼"
      }
    }

     

    2.抽象类&抽象方法

    (1)抽象类

    标准:一个类要求它的字类必须包含指定方法,它是提供其他类继承的基类,不能被直接实例化。

    定义抽象类:

    abstract class Animal {
      abstract eat():any ;
    }
    
    let a=new Animal();  // 报错:无法创建抽象类的实例

     (2)抽象方法

    抽象方法在子类里面必须实现

    // 父类
    abstract class Animal {
      public name: string;
      constructor(name: string) {
        this.name = name;
      }
    
      abstract eat(): any;
    }
    // 子类Dog
    class Dog extends Animal {
      constructor(name: string) {
        super(name);
      }
      // 抽象类的子类必须实现抽象类里面的抽象方法
      eat() {
        console.log(this.name + '在吃肉');
      }
    }
    let d = new Dog('达摩');
    d.eat();
    
    // 子类Cat
    class Cat extends Animal {       
      constructor(name: string) {
        super(name);
      }
    }

    子类Cat不实现eat()方法,会报错:非抽象类“Cat”不会实现继承自“Animal”类的抽象成员“eat”,即子类Cat不会自动继承父类的方法

  • 相关阅读:
    Python print "hello world" SyntaxError: invalid syntax
    Parencodings(模拟)
    Do the Untwist(模拟)
    Jugs(回溯法)
    Anagrams by Stack(深度优先搜索)
    Fire Net(深度优先搜索)
    Integer Numbers
    Codeforces Beta Round #34 (Div. 2) E. Collisions
    什么是Qt Widget?
    codeblocks快捷键(转)
  • 原文地址:https://www.cnblogs.com/codexlx/p/12770724.html
Copyright © 2011-2022 走看看