Liskov substitution principle (LSP): Derived classes must be substitutable for their base classes. -- proposed by Barbara Liskov
LSP sounds the same as substitutability but it goes beyond substitutability; LSP implies that a subclass should not be more restrictive than the behavior specified by the superclass. As you know, Java has language support for substitutability. However, if LSP is not followed, substituting a subclass object for a superclass object can break the functionality of the code.
Suppose the Payroll class depends on the adjustMySalary(int percent) method of the Staff class. Furthermore, the Staff class states that the adjustMySalary method will work for all positive percent values. Both the Admin and Academic classes override the adjustMySalary method.
Now consider the following:
- The
Admin#adjustMySalarymethod works for both negative and positive percent values. - The
Academic#adjustMySalarymethod works for percent values1..100only.
In the above scenario,
- The
Adminclass follows LSP because it fulfillsPayroll’s expectation ofStaffobjects (i.e., it works for all positive values). SubstitutingAdminobjects forStaffobjects will not break thePayrollclass functionality. - The
Academicclass violates LSP because it will not work for percent values over100as expected by thePayrollclass. SubstitutingAcademicobjects forStaffobjects can potentially break thePayrollclass functionality.