class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
class Dog extends Animal {
constructor(name: string) {
super(name);
}
bark() {
console.log(`${this.name} barks.`);
}
}
class Cat extends Animal {
constructor(name: string) {
super(name);
}
meow() {
console.log(`${this.name} meows.`);
}
}
// 使用构造函数构建对象
const myDog = new Dog('Buddy');
const myCat = new Cat('Whiskers');
// 调用各自的方法和继承自基类的方法
myDog.speak();
myDog.bark();
myCat.speak();
myCat.meow();