如果派生类的构造函数签名与基类不同,是否违反了 oop 原则(例如,Liskov 原则)?
class Base {
protected x: number;
protected y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
class Derived extends Base {
private text: string;
constructor(text: string, x: number, y: number) {
super(x, y);
this.text = text;
}
}
最佳答案
不,不是,因为 Liskov 原则谈到“子类型中方法参数和返回类型的逆变”。当你做这样的事情时:
foo(bar:Base){
//do stuff
}
此方法需要 Base
类的实例,而不是构造函数,因此方法的逆变不适用于这种情况。
如果你这样做会违反这个原则,因为 Base
实例不能被 Extended
实例替换:
class Base{
foo():string{
return "";
}
bar(arg:string){}
}
class Extended extends Base{
foo():number{
return 1;
}
bar(arg:boolean){}
}
但是 typescript 编译器不允许这样做。
关于oop - 派生类的不同构造函数签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43067415/