U
U
user_of_toster2021-04-26 16:26:57
OOP
user_of_toster, 2021-04-26 16:26:57

Is narrowing the scope of parent class arguments a violation of LSP?

class Parent {
     constructor(public arg: any){}
}

class Child extends Parent {
    constructor(public arg: number){}
}

The LSP states that members of a superclass can be replaced by instances of a subclass and the program will still work correctly. Does this apply to class constructors? Can subclass constructors narrow down the scope of the arguments the superclass takes?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vasily Bannikov, 2021-04-26
@user_of_toster

This does not violate LSP, since the constructor is not an instance method.

V
Vitsliputsli, 2021-04-27
@Vitsliputsli

Of course, it violates:
1) Despite everything that has been written here, a constructor is an instance method. Let with a special syntactic call, but no more, and more importantly, this is a public method. A constructor is just syntactic sugar, if it weren't for it, you would have to call a similar method manually after each object creation.
2) Compliance with the principle is checked very easily, substitute the parent instance instead of the child and check that the behavior has not changed. In your case, it is obvious that the behavior will change, and therefore the principle is violated.
3) The fact that some language-specific types are used does not matter at all, change to hereditarily dependent classes and it will be the same. In your version, if it were the other way around and the heir had a wider type, i.e. was countervariant, it would not violate the principle.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question