TypeScript-多态篇

在这里插入图片描述

TypeScript中的多态
//多态:父类定义一个方法不去实现,让继承它的子类去实现  每一个子类有不同的表现 
//多态属于继承
class Animal {
	name: string = 'm';
	constructor(name: string) {
	}
	eat() {
	    console.log(`这是吃的方法`);
	}
}
		
class Dog extends Animal {
	constructor(name: string) {
		   super(name);
	}
	eat() {
		        console.log(`${this.name}喜欢吃肉`)
	}
}

let dog = new Dog('小狗');

dog.eat(); //小狗喜欢吃肉
		
class Cat extends Animal {
		constructor(name: string) {
		    super(name);
		}
		eat() {
		        console.log(`${this.name}喜欢吃老鼠`)
	        }
}

let cat = new Cat('小猫')

cat.eat() //小猫喜欢吃鱼

谢谢观看 !!! 如有不足,敬请指教

猜你喜欢

转载自blog.csdn.net/handsomezhanghui/article/details/107459931
今日推荐