abstract class Animal {
private name!: string
private age: number
constructor(name: string, age: number) {
this.name = name
this.age = age
}
// 抽象方法,实现类必须要定义和传入对应的参数
abstract eat(eat: string): void;
// 通过这个导入出去,外面访问this.name
getName() {
return this.name
}
getAge() {
return this.age
}
run() :void{
console.log("父类方法,子类可以不实现直接调用,也可以重写");
}
}
class Dog extends Animal {
constructor(name: string, age: number) {
super(name, age)
}
eat(eat: string): void {
console.log(`动物的名字是:${this.getName()}, 年龄:${this.getName()},吃的食物是:${eat}`);
}
run(): void {
console.log("子类重写了自己的方法");
}
}
const dog1 = new Dog('旺财', 3)
dog1.eat('狗粮')
dog1.run()
typescript抽象类里面定义多个private时,如何让实现类访问里面的数据
于 2024-04-29 14:43:52 首次发布