TS中的抽象类

文章类型:TypeScript

发布者:hp

发布时间:2022-10-17

TS中,抽象类(abstract)描述的是一种抽象的概念,无法被实例化,不能通过关键字new创建,只能被继承,并且抽象方法必须被子类实现。

特点:

1:抽象类中分为抽象属性/方法和普通属性/方法;

2:抽象类不能被实例化,只能被继承;

3:抽象类继承在抽象类中,可以不实现,但是如果继承的非抽象类中,必须实现抽象类中的抽象方法;

namespace a {
abstract class Animate {
abstract name: string
age: number
constructor(age: number) {
this.age = age
}
abstract eat(): void
run() {
console.log('年龄' + this.age)
}
}
class Dog extends Animate {
name: string = '小黄'
eat() {
console.log(this.name + 'eat')
}
run() {
console.log("重写run")
}
}
}

直接实例化,会报错

 const abAni:Animate=new Animate() // Cannot create an instance of an abstract class

非抽象类不继承抽象类中的方法,会报错

 class Dog extends Animate{ //Non-abstract class 'Dog' does not implement inherited abstract member 'eat' from class 'Animate'
name:string='小黄'
// eat(){
// console.log(this.name+'eat')
// }
run(){
console.log("重写run")
}
}

const ani:Animate=new Dog(100)

抽象类中的普通方法和属性可以在非抽象类中可继承或者不继承,也可以被重写

  class Dog extends Animate{
name:string='小黄'
constructor(age:number){
super(age)
}
run(){
console.log("重写run")
}
eat(){
console.log(this.name+'eat')
}
}
const ani:Animate=new Dog(100)
console.log(ani.age) //100
ani.run() //重写run

}

抽象类继承可以不实现抽象类的抽象方法,但是非抽象类一定要实现,否则报错

abstract class Cat extends Animate {
abstract sex: string
run() {
console.log('run2')
}
}
class bigCat extends Cat {
name: string = '小猫'
sex: string = '女'
eat() {

}

}

const whiteCat: Cat = new bigCat(100)
console.log(whiteCat.age) //100
console.log(whiteCat.name)//小猫
console.log(whiteCat.sex)//女
whiteCat.run()