面试题答案
一键面试class Shape {
constructor(color) {
this.color = color;
}
static getType() {
return 'Shape';
}
}
class Rectangle extends Shape {
constructor(color, width, height) {
super(color);
this.width = width;
this.height = height;
}
static getType() {
return 'Rectangle';
}
}
实现思路
- 在
Shape
类中直接定义静态方法getType
,返回字符串'Shape'
。 - 在
Rectangle
类中重写getType
静态方法,返回字符串'Rectangle'
。这样Rectangle
类及其实例在调用getType
方法时,会调用自身重写的方法,返回'Rectangle'
,而Shape
类调用getType
方法时,返回'Shape'
。
原理
- 静态方法:静态方法属于类本身,而不属于类的实例。通过在类中使用
static
关键字定义静态方法,所有该类的实例都可以通过类名来访问这个静态方法。 - 方法重写:在继承体系中,子类可以重写从父类继承来的方法。当子类调用这个方法时,会优先调用子类自身重写的方法,而不是父类的方法。所以
Rectangle
类重写getType
方法后,Rectangle
类及其实例调用getType
方法会返回'Rectangle'
,而Shape
类调用getType
方法会返回'Shape'
。