DEV Community

Cover image for Revisiting the L in SOLID
Elyess Eleuch
Elyess Eleuch

Posted on

Revisiting the L in SOLID

Photo by Pavel Nekoranec on Unsplash
Alt Text
This is a continuation of the SOLID. In the last post, I covered the O and now we will be continuing with the L. So if you didn't check the last post, feel free to click on the link:

Liskov substitution principle

Let z be a property provable about objects x of type T. Then z should be true for objects y of type S where S is a subtype of T.

In a nutshell: A has a property A, if B is a subtype of A then B has also the property A and B should behave the way A is expected to behave. And that means any derived class (B) should be able to substitute its parent class (A) without the consumer knowing it.


Let's suppose we have a car Class and two other classes Ferrari and Bugatti. Both of the cars are should behave like a normal car would do, right?

public class Car {
    public int speed;

    public Car(int speed) {
        this.speed = speed; 

public class Bugatti extends Car {
    public Bugatti (int speed) {

public class Ferrari extends Car {
    public Ferrari (int speed) {
Enter fullscreen mode Exit fullscreen mode

And now let's suppose we want to customize a car by increasing its speed, usually, we would write a method inside the Car like this:

   public void increaseSpeed(Car car) {
        String message = "You increased the speed of " + car.getClass().getSimpleName()  + " from " + car.speed;

Enter fullscreen mode Exit fullscreen mode

Please notice that increaseSpeed takes any car as a parameter.
We didn't have to implement this method in each class (Ferrari and Bugatti) because they should behave the superclass (car) would. No Complications. And that's the Liskov Substitute Pattern. We replaced the car argument with one of the subtypes each time, and nothing has changed.
Now let's check our results:

You increased the speed of Bugatti from 200
You increased the speed of Ferrari from 210
Enter fullscreen mode Exit fullscreen mode


The Liskov Substitution Principle extends the open/closed principle by preventing breaking client code.

Sources :

Meyer, B. (1997): Object-Oriented Software Construction, 2nd edition
Robert C. Martin “Principles of OOD”

Top comments (2)

mcsee profile image
Maxi Contieri

great article!

why is the method increaseSpeed static?

I think it is more easy to explain Liskovs with non-static methods, and you should also skip the metaprogramming part.

Static methods and metaprogramming are code smells

sightlessdog profile image
Elyess Eleuch

Hi, thanks or your feedback. You're totally right!. I would adjust the static part, and I used reflection in the increaseSpeed method to only simplify the output.