Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Oop 派生类的不同构造函数签名_Oop_Typescript - Fatal编程技术网

Oop 派生类的不同构造函数签名

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

如果派生类的构造函数签名与基类不同,是否违反了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
实例不能被
扩展的
实例替换:

类基{
foo():字符串{
返回“”;
}
条(arg:string){}
}
类扩展扩展基{
foo():数字{
返回1;
}
条(arg:boolean){}
}
但是typescript编译器不允许这样做