类的继承
class Animal{
name:string
age:number
constructor(name:string,age:number){
this.name = name
this.age = age
}
sing(jiao:string){
console.log(jiao);
}
}
/*
定义一个狗的类
// dog1 继承 Animal 类
*/
class dog1 extends Animal{
}
/*
定义一个猫的类
// cat 继承 Animal 类
*/
class cat1 extends Animal{
}
const dog2 = new dog1('小狗',2)
console.log(dog2);
const cat2 = new cat1('小猫',3)
console.log(cat2);
cat2.sing('喵喵喵')
cat2.sing('汪汪汪')
super,抽象类
/*
以 abstract => 抽象类
不能用来 创建 对象
抽象类 => 用来被继承的 类
抽象类 中 => 可以添加 抽象方法
*/
abstract class doing {
food: string
constructor(food: string) {
this.food = food
}
// 定义一个抽象方法
// 抽象方法使用 abstract 开头,没有方法体
// 抽象方法 => 只能 定义在 抽象类 中,子类方法 必须对 父类方法 进行重写
abstract eat():void
}
class toDoing extends doing {
age: number
constructor(age: number, name: string) {
// 如果 在子类中, 写了 构造函数
// 在子类的构造函数中,必须对父类的函数进行调用
super(name) // => 调用父类的 构造函数
this.age = age
}
eat() {
// 在 类 的方法中,super 就表示 当前类的父类
// super 引用 父类 方法
// super.eat()
console.log("我讨厌")
}
}
const a = new toDoing(1, "面包")
console.log(a)
a.eat()
const b = new doing("热干面") // => 报错
console.log(b)
/*
doing 以 abstract 开头=> 抽象类
不能用来 创建 对象
抽象类 => 用来被继承的 类
*/