Liskov Substitution Principle

What is the Liskov Substitution Principle?

Example without using the Liskov Substitution Principle.

public class LiskovSubstituteTest {
public static void Main(string[] args) {

Apple apple = new Orange();
System.out.println(apple.getColor());
}
}
public class Apple { public String getColor() {
return "Red";
}
}
public class Orange : Apple {

public String getColor() {
return "Orange";
}
}

Example using the Liskov Substitution Principle

public abstract class Fruit {
public abstract String getColor();
}
public class Apple extends Fruit {    @Override
public String getColor() {
return "Red";
}
}
public class Orange extends Fruit { @Override
public String getColor() {
return "Orange";
}
}
public class LiskovSubstituteTest {

public static void Main(String[] args) {

Fruit fruit = new Orange();
System.out.println(fruit.getColor());

fruit = new Apple();
System.out.println(fruit.getColor());
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store