Reputation: 11
I'm puzzling around this question. I would be happy to know which is the correct answer and why?
Liskov Substitution Principle states that it is allowed to weaken preconditions in overriden methods. What can happen in a program where a subclass strengthens preconditions in a overriden method?
Thanks in advice!
Upvotes: 0
Views: 98
Reputation: 10064
A strengthened precondition sets a tighter bound on the possible values that can be passed to the method. In other words, the domain of the overridden method is a subset of the domain of the base class's method. Therefore:
If the strengthened precondition doesn't fail (i.e. if the calling code passed a value in the subset accepted by the strengthened precondition), then the method would return the same result as it would've for the base class's method (as required by the LSP). Therefore, the calling code can't break after the call.
This is the correct answer. Consider a method defined for any integers, which is overridden to accept only positive integers. The calling could would not be aware of the strengthened precondition since it's accessing the subclass polymorphically, and if it passed a negative integer (which was valid previously), the call would fail for the overridden method of the subclass.
This may be the case but isn't necessarily true.
This may be the case but isn't necessarily true.
For further reading, see Wikipedia: Covariance and contravariance - Covariant method argument type
Upvotes: 0
Reputation: 1347
I'd go with:
Upvotes: 2