ts中的方法重写
文章类型:TypeScript
发布者:hp
发布时间:2023-05-27
1:使用方法重写来修改父类中已经存在的方法的实现。
2:允许子类重新定义父类中的方法,并在子类的实例中使用新的实现
1:子类必须继承自父类
2:子类中的方法名称、参数列表和返回类型必须与父类中被重写的方法一致
1:直接覆盖方式
class Animal {
move(): void {
console.log("The animal is moving.");
}
}
class Dog extends Animal {
move(): void {
console.log("The dog is running.");
}
}
const animal = new Animal();
animal.move(); // 输出: The animal is moving.
const dog = new Dog();
dog.move(); // 输出: The dog is running.
2:使用 super 关键字,显示调用
只能在派生类的方法中使用,只能用于调用父类中的方法
构造函数中调用父类的构造函数:通过 super() 可以调用父类的构造函数,并传递必要的参数。
普通方法中调用父类的方法:通过 super.methodName() 可以调用父类中指定的方法。
静态方法中调用父类的静态方法:通过 super.methodName() 可以调用父类中指定的静态方法
class Animal {
protected name: string;
constructor(name: string) {
this.name = name;
}
move(): void {
console.log("The animal is moving.");
}
}
class Dog extends Animal {
private breed: string;
constructor(name: string, breed: string) {
super(name); // 调用父类的构造函数
this.breed = breed;
}
move(): void {
super.move(); // 调用父类的 move 方法
console.log("The dog is running.");
}
static create(name: string, breed: string): Dog {
const dog = new Dog(name, breed);
// 在静态方法中调用父类的静态方法
Animal.logCreation();
return dog;
}
static logCreation(): void {
console.log("A dog instance is created.");
}
}
const dog = new Dog("Max", "Labrador");
dog.move(); // 输出:
// The animal is moving.
// The dog is running.
const anotherDog = Dog.create("Buddy", "Golden Retriever");
// 输出:
// A dog instance is created.
1:在子类中根据具体的需求来定制和扩展父类的行为,以满足不同的业务逻辑需求