The Liskov Substitution principle was introduced by Barbara Liskov in her conference keynote “Data abstraction” in 1987.
It states that objects of a superclass should be replaceable with objects of its subclass without affecting the functionality of the program.
Let's move on to our examples of musicians. Given that the situation involves a base class called "Musician" and child classes called "Singer," "Guitarist," and "Drummer," the Liskov Substitution Principle states that any behaviours or methods provided in the base class should be compatible with instances of the child classes without resulting in unexpected behaviour.
For example, if the base class "Musician" has a method called "play," the child classes "Singer," "Guitarist," and "Drummer" should be able to implement this method in a way that is suitable for their type of musician.
Let's demonstrate the Liskov Substitution Principle in action, as the child classes can be used interchangeably with the base class without affecting the functionality of the program:
abstract class Musician {
abstract play(): void;
}
class Singer extends Musician {
public play() {
console.log("Singer is singing");
}
}
class Guitarist extends Musician {
public play() {
console.log("Guitarist is playing the guitar");
}
}
class Drummer extends Musician {
public play() {
console.log("Drummer is playing the drums");
}
}
// Creating instances of the musician
const singer = new Singer();
const guitarist = new Guitarist();
const drummer = new Drummer();
// Using the play method on each instance of musician
singer.play();
guitarist.play();
drummer.play();
In this example, the abstract class "Musician" has an abstract method "play" which is implemented in each of the concrete classes "Singer," "Guitarist," and "Drummer".
See you in the next article of this series.