// 多态: 父类型的引用指向了子类型的对象 ,不同类型的对象针对相同的方法,产生了不同的行为 (() => { //定义一个父类 class Animal { name: string //定义一个构造函数 constructor(name: string) { this.name = name } //方法 run(distance: number = 0) { console.log(`run ${distance} far away`,this.name) } } //定义一个子类 class Dog extends Animal{ //构造函数 constructor(name: string){ //调用父类的构造函数 实现子类中属性的初始化操作 super(name) } //实例的方法 run(distance: number = 10): void { console.log(`run ${distance} far away`,this.name) } } class Pig extends Animal { //构造函数 constructor(name: string){ super(name) } run(distance: number = 20): void { console.log(`run ${distance} far away`,this.name) } } //实例化父类的对象 const ani: Animal = new Animal('动物') ani.run() //实例化子类对象 const dog: Dog = new Dog('大黄') dog.run() const pig: Pig = new Pig('佩奇') pig.run() /* 父类和子类的关系 可以通过父类的类型 创建子类的类型 */ const dog1: Animal = new Dog('小黄') const pig1: Animal = new Pig('乔治') dog1.run() pig1.run() /* 函数 */ function showRun(ani: Animal){ ani.run() } showRun(dog1) showRun(pig1) })()