1.多态:父类定义一个方法不去实现,让继承他的子类去实现,每一个子类有不同的表现;
// 就像《猫和老鼠》中,斯派克欺负汤姆,汤姆欺负杰瑞一样// 通俗点讲就是,猫和狗都属于动物类,你不能说只要是动物就喜欢吃肉,那牛羊还吃草呢!就像狗吃屎、猫吃老鼠一样// 多态属于继承class Animal { name: string; constructor(name: string) { this.name = name; } eat() { //具体吃什么不知道, 具体吃什么由继承他的子类去实现,每一个子类的表现不一样 console.log(this.name + ",吃什么呢你?"); }}class Dog extends Animal { constructor(name: string) { super(name); } eat() { return this.name + ",吃屎吧你"; }}class Cat extends Animal { constructor(name: string) { super(name); } eat() { return this.name + ",你又欺负杰瑞了?"; }}let c = new Cat("汤姆");let d = new Dog("嘿");alert(c.eat());alert(d.eat());
2.抽象类:
- typescript中的抽象类,它是提供其他类继承的基类,不能直接被实例化;
2.用abstract关键字定义抽象类和抽象方法,抽象类中的抽象方法不包含具体实现并且必须在派生类中实现;
3.abstract 抽象方法只能放在抽象类里面
4.抽象类和抽象方法用来定义标准,标准:Animal这个类要求它的子类必须包含eat方法;//typescript中的抽象类,它是提供其他类继承的基类,不能直接被实例化;abstract class Animal {public name: string;constructor(name: string) { this.name = name;}abstract eat(): any;}let a=new Animal("???");//错误写法

// abstract 抽象方法只能放在抽象类里面class Animal { public name: string; constructor(name: string) { this.name = name; } abstract eat(): any; run() { console.log("其他方法可以不实现!"); }}

//抽象类和抽象方法用来定义标准,标准:Animal这个类要求它的子类必须包含eat方法;// 标准:abstract class Animal { public name: string; constructor(name: string) { this.name = name; } abstract eat():any;//抽象方法不包含具体实现并且必须在派生类中实现;}class Dog extends Animal { //抽象类的子类必须实现抽象类里面的抽象方法 constructor(name: string) { super(name); }}let d = new Dog("杰克");//正确abstract class Animal { public name: string; constructor(name: string) { this.name = name; } abstract eat(): any;}class Dog extends Animal { constructor(name: string) { super(name); } eat() {// 抽象类和抽象方法用来定义标准,标准:Animal这个类要求它的子类必须包含eat方法; return this.name + ",你始终改不了吃屎的毛病啊!"; }}let d = new Dog("杰克");alert(d.eat());
