Oop 派生类的不同构造函数签名
如果派生类的构造函数签名与基类不同,是否违反了oop原则(例如Liskov原则)Oop 派生类的不同构造函数签名,oop,typescript,Oop,Typescript,如果派生类的构造函数签名与基类不同,是否违反了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(t
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
实例不能被扩展的实例替换:
类基{
foo():字符串{
返回“”;
}
条(arg:string){}
}
类扩展扩展基{
foo():数字{
返回1;
}
条(arg:boolean){}
}
但是typescript编译器不允许这样做