【Typescript】Abstract class, abstract method and polymorphism in ts

Abstract classes, abstract methods and polymorphism in Typescript

The abstract class in typescript is a base class that provides inheritance for other classes and cannot be instantiated

Use the abstract keyword to define abstract classes and abstract methods. The abstract methods in the abstract class do not contain concrete implementations and must be implemented in derived classes (that is, the Animal class is defined as an abstract class and abstract method using the abstract keyword, but the abstract method must be in its Implemented in the Dog class that inherits the Animal class)

This approach is similar to polymorphism : the parent class defines a method and does not implement it, let the inherited subclasses implement it, and each subclass has a different form of expression

Abstract classes and abstract methods

//Animal是一个抽象类,因为他使用了abstract关键字,里面含有一个eat()抽象方法
abstract class Animal {
    
    
    name: string
    constructor(name: string) {
    
    
        this.name = name
    }
    abstract eat(): any  //抽象方法前有abstract关键字,抽象方法不包含具体实现,要在继承的子类中实现
    run() {
    
       //非抽象方法
        console.log('非抽象方法');
    }
}
 //Dog中继承了抽象类Animal,所以必须实现父类抽象方法,否则编译报错
class Dog extends Animal {
    
    
    constructor(name: string) {
    
    
        super(name)
    }
    eat() {
    
    
        console.log(this.name + "吃肉")
    }
    
}

var dog = new Dog("狗")
dog.eat()

polymorphism

//多态:父类定义一个方法不去实现,让继承它的子类去实现  每一个子类有不同的表现  多态属于继承

class Animal {
    
    
    name: string
    constructor(name: string) {
    
    
        this.name = name
    }
    eat(){
    
    
        console.log('吃方法')  //具体吃什么不知道,等待继承它的子类去实现
    } 
}
class Dog extends Animal {
    
    
    constructor(name: string) {
    
    
        super(name)
    }
    eat() {
    
    
        return this.name + "吃肉"
    }
    
} 
class Cat extends Animal{
    
    
    eat(){
    
    
        return this.name+"吃老鼠"
    }
}
// 每一个子类有不同的表现
// let p = new Cat('猫')
// console.log(p.eat()); 输出猫吃老鼠
let p = new Dog('狗')
console.log(p.eat()); //输出狗吃肉

Guess you like

Origin blog.csdn.net/m0_63779088/article/details/126471350