LSP quy định rằng các object của subclass phải có thể thay thế object của superclass mà không làm hỏng tính đúng đắn của chương trình.
Ví dụ vi phạm kinh điển: class Rectangle có setWidth/setHeight, class Square extends Rectangle override cả hai để giữ tỷ lệ — khi code gọi setWidth(5) trên Square kỳ vọng height không đổi nhưng thực tế height cũng thay đổi, phá vỡ kỳ vọng. Dấu hiệu vi phạm LSP: subclass override method rồi throw exception, hoặc kiểm tra instanceof trước khi gọi method. Cách sửa: tách interface, dùng composition thay inheritance, hoặc tái thiết kế hierarchy.
LSP states that objects of a subclass must be substitutable for objects of the superclass without breaking program correctness.
- The classic violation:
RectanglehassetWidth/setHeight, andSquare extends Rectangleoverrides both to keep the aspect ratio — when code callssetWidth(5)on aSquareand expects height to remain unchanged, it silently breaks. - Warning signs of LSP violations include subclasses overriding a method to throw an exception, or callers checking
instanceofbefore invoking a method. - Fixes include splitting interfaces, favoring composition over inheritance, or redesigning the hierarchy.
- LSP ensures that code depending on an interface doesn't need to know about concrete implementations.