TS中的多态
概念:多态值得之父类型的引用指向了子类型的对象,不同类型的对象针对相同的方法,产生了不同的行为。
示例:
(()=>{
// 定义一个父类
class Animal {
// 定义一个属性
name:string
// 定义一个构造函数
constructor(name:string){
this.name = name
}
// 定义方法
sayRunDistance(distance:number = 0){
console.log(`我跑了${distance}米!!!!!!`)
}
}
//定义一个子类1
class Dog extends Animal {
// 构造函数
constructor (name:string) {
// 调用父类的构造函数,实现子类中属性的初始化操作
super(name)
}
// 实例方法,重写父类中的实例方法
sayRunDistance(distance:number = 5) {
console.log(`我跑了${distance}米!!!!!!`)
}
}
//定义一个子类2
class Cat extends Animal {
// 构造函数
constructor (name:string) {
// 调用父类的构造函数,实现子类中属性的初始化操作
super(name)
}
// 实例方法,重写父类中的实例方法
sayRunDistance(distance:number = 10) {
console.log(`我跑了${distance}米!!!!!!`)
}
}
// 实例化父类对象
const Animal = new Animal ('辛巴')
Animal.sayRunDistance()
// 实例化子类对象1
const Dog = new Dog('哈士奇')
Dog .sayRunDistance()
// 实例化子类对象2
const Cat = new Cat ('布偶猫')
Cat .sayRunDistance()
// 父类型和子类型的关系:父子关系,此时,父类类型创建子类的对象
const Dog1 :Animal = new Dog('金毛')
const Cat1 :Animal = new Cat('暹罗猫')
Dog1.sayRunDistance()
Cat1.sayRunDistance()
})
多态的作用:
// 定义一个函数,该函数需要的参数是Animal类型的
function showRun (ani:Animal){
ani.sayRunDistance()
}
// 此时将Animal的子类作为参数传进去
showRun(Dog1)
showRun(Cat1)