3_多态.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // 多态: 父类型的引用指向了子类型的对象 ,不同类型的对象针对相同的方法,产生了不同的行为
  2. (() => {
  3. //定义一个父类
  4. class Animal {
  5. name: string
  6. //定义一个构造函数
  7. constructor(name: string) {
  8. this.name = name
  9. }
  10. //方法
  11. run(distance: number = 0) {
  12. console.log(`run ${distance} far away`,this.name)
  13. }
  14. }
  15. //定义一个子类
  16. class Dog extends Animal{
  17. //构造函数
  18. constructor(name: string){
  19. //调用父类的构造函数 实现子类中属性的初始化操作
  20. super(name)
  21. }
  22. //实例的方法
  23. run(distance: number = 10): void {
  24. console.log(`run ${distance} far away`,this.name)
  25. }
  26. }
  27. class Pig extends Animal {
  28. //构造函数
  29. constructor(name: string){
  30. super(name)
  31. }
  32. run(distance: number = 20): void {
  33. console.log(`run ${distance} far away`,this.name)
  34. }
  35. }
  36. //实例化父类的对象
  37. const ani: Animal = new Animal('动物')
  38. ani.run()
  39. //实例化子类对象
  40. const dog: Dog = new Dog('大黄')
  41. dog.run()
  42. const pig: Pig = new Pig('佩奇')
  43. pig.run()
  44. /* 父类和子类的关系 可以通过父类的类型 创建子类的类型 */
  45. const dog1: Animal = new Dog('小黄')
  46. const pig1: Animal = new Pig('乔治')
  47. dog1.run()
  48. pig1.run()
  49. /* 函数 */
  50. function showRun(ani: Animal){
  51. ani.run()
  52. }
  53. showRun(dog1)
  54. showRun(pig1)
  55. })()