Grokking SOLID Design Principles
Vote

0% completed

​

Break The Hierarchy for Adhering to LSP

In the previous lesson, we identified the problem where the ElectricCar class violated the Liskov Substitution Principle by failing to implement the refuel() method properly. Now, we will redesign the inheritance hierarchy to follow LSP by introducing a generalized Vehicle class.

Step 1: Create a General Vehicle Class

We’ll begin by creating a generalized Vehicle class, which defines common behaviors shared by all vehicles, such as starting and stopping, and an abstract refuel() method for specific fuel/energy behavior.

The `Vehicle

.....

.....

.....

Like the course? Get enrolled and start learning!
A

Anonymous

· 2 years ago

public class ElectricCar : Car {

public override void refuel() {        

    reCharge()

}

private void reCharge() {

    Console.WriteLine("Car is recharging");

}

}

public class ElectricCar : Vehicle {

public override void refuel() {        

    recharge();

}   

private void recharge() {

    Console.WriteLine("Electric car is recharging");

}

}

A

Anonymous

· 2 years ago

The Liskov Substitution Principle (LSP) is a fundamental principle in object-oriented programming that states that objects of a superclass should be able to be replaced with objects of a subclass without affecting the correctness of the program.

This ensures that the Liskov Substitution Principle is followed: an instance of ElectricCar can replace Car without causing issues.

 We didn't replace superclass object with subclass object in this case. We just replace it with another subclass object?

Reading Progress

0%


Vote for new content