抽象类
abstract开头的类是抽象类
抽象类和其他类区别不大,只是不能用来创建对象
抽象类就是专门用来被继承的类,不能创建实例
abstract class Animal{
name:string;
constructor(name:string){
// 在实例方法中,this就表示当前的实例
// 在构造函数中当前对象就是当前新建的那个对象
// 可以通过this向新建的对象中添加属性
this.name = name;
}
sayHello(){
// 在方法中可以通过this来表示当前调用方法的对象
console.log('rrrr');
}
}
// 使Dog类继承Animal类
// Animal被称为父类,Dog被称为子类
class Dog extends Animal{
sayHello(){
console.log('www');
}
}
const dog = new Dog('name1');
dog.sayHello();
抽象方法
抽象类中可以添加抽象方法
抽象方法使用abstract开头,没有方法体
抽象方法只能定义在抽象类中,子类必须对抽象方法进行重写
abstract class Animal{
name:string;
constructor(name:string){
this.name = name;
}
// 定义一个抽象方法
abstract sayHello():void;
}
class Dog extends Animal{
sayHello(){
console.log('www');
}
}
const dog = new Dog('name1');
dog.sayHello();