1.多态:父类定义一个方法不去实现,让继承他的子类去实现,每一个子类有不同的表现;

  1. // 就像《猫和老鼠》中,斯派克欺负汤姆,汤姆欺负杰瑞一样
  2. // 通俗点讲就是,猫和狗都属于动物类,你不能说只要是动物就喜欢吃肉,那牛羊还吃草呢!就像狗吃屎、猫吃老鼠一样
  3. // 多态属于继承
  4. class Animal {
  5. name: string;
  6. constructor(name: string) {
  7. this.name = name;
  8. }
  9. eat() {
  10. //具体吃什么不知道, 具体吃什么由继承他的子类去实现,每一个子类的表现不一样
  11. console.log(this.name + ",吃什么呢你?");
  12. }
  13. }
  14. class Dog extends Animal {
  15. constructor(name: string) {
  16. super(name);
  17. }
  18. eat() {
  19. return this.name + ",吃屎吧你";
  20. }
  21. }
  22. class Cat extends Animal {
  23. constructor(name: string) {
  24. super(name);
  25. }
  26. eat() {
  27. return this.name + ",你又欺负杰瑞了?";
  28. }
  29. }
  30. let c = new Cat("汤姆");
  31. let d = new Dog("嘿");
  32. alert(c.eat());
  33. alert(d.eat());

2.抽象类:

  1. typescript中的抽象类,它是提供其他类继承的基类,不能直接被实例化;
    2.用abstract关键字定义抽象类和抽象方法,抽象类中的抽象方法不包含具体实现并且必须在派生类中实现;
    3.abstract 抽象方法只能放在抽象类里面
    4.抽象类和抽象方法用来定义标准,标准:Animal这个类要求它的子类必须包含eat方法;
    1. //typescript中的抽象类,它是提供其他类继承的基类,不能直接被实例化;
    2. abstract class Animal {
    3. public name: string;
    4. constructor(name: string) {
    5. this.name = name;
    6. }
    7. abstract eat(): any;
    8. }
    9. let a=new Animal("???");//错误写法
    image.png
  1. // abstract 抽象方法只能放在抽象类里面
  2. class Animal {
  3. public name: string;
  4. constructor(name: string) {
  5. this.name = name;
  6. }
  7. abstract eat(): any;
  8. run() {
  9. console.log("其他方法可以不实现!");
  10. }
  11. }

image.png

  1. //抽象类和抽象方法用来定义标准,标准:Animal这个类要求它的子类必须包含eat方法;
  2. // 标准:
  3. abstract class Animal {
  4. public name: string;
  5. constructor(name: string) {
  6. this.name = name;
  7. }
  8. abstract eat():any;//抽象方法不包含具体实现并且必须在派生类中实现;
  9. }
  10. class Dog extends Animal {
  11. //抽象类的子类必须实现抽象类里面的抽象方法
  12. constructor(name: string) {
  13. super(name);
  14. }
  15. }
  16. let d = new Dog("杰克");
  17. //正确
  18. abstract class Animal {
  19. public name: string;
  20. constructor(name: string) {
  21. this.name = name;
  22. }
  23. abstract eat(): any;
  24. }
  25. class Dog extends Animal {
  26. constructor(name: string) {
  27. super(name);
  28. }
  29. eat() {// 抽象类和抽象方法用来定义标准,标准:Animal这个类要求它的子类必须包含eat方法;
  30. return this.name + ",你始终改不了吃屎的毛病啊!";
  31. }
  32. }
  33. let d = new Dog("杰克");
  34. alert(d.eat());

image.png