
The Principle section of the LSP Wikipedia article explains this very well, so I’m going to quote it here: The ArrayList is an implementation of the List interface, therefore, when the program runs, the customer repository will not see that the type is of ArrayList, but as an instance of List. The reason is that the customer repository is depending upon the contract provided by the List interface.
Liskov substitution principle code#
In other words, in the code above, we’ve depended upon an abstraction ( List), and because of that we can supply a subtype ( ArrayList) and the program will still run without an issue. Since ArrayList is a subtype of List, the program will not falter: We’re replacing the instance of the requested type ( List) with an instance of its subtype ( ArrayList). This is the Liskov Substitution Principle at work. Wait a second…the customer repository needs a List, not a ArrayList. Get the ids somehow (loop, lookup, etc) ArrayList ids = getCustomerIds () List customers = customerRepository. The compiler is also very good at allowing us to write code that adheres to the Liskov Substitution Principle. You try to assign a String to a Long or vice versa, and the compiler tells you you’ve made a mistake.

The compiler is very good at catching type errors and notifying us via the errors that it reports. An Example of Replacing Object Instance with Subtypes You probably have even written code that adheres to the LSP. The thing is, this principle is very easy to understand and you use it all the time without knowing it. Unfortunately (or fortunately - depends on how you look at it), if you dig deeper into the Wikipedia entry on the Liskov Substitution Principle you’ll find that the article dives fairly deeply into some deep computer science, with links that branch out all over the place. I’m sure you’re like me and you probably read it many times trying to figure out what that means only to find that you’re probably confusing yourself further and further by doing so. Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program. The Liskov Substitution Principle states the following: The Liskov Substitution Principle was introduced by Barbara Liskov in 1987 in a keynote at a conference.

The third letter in the SOLID mnemonic acronym is L, which is for the Liskov Substitution Principle (LSP). If you missed part 1 or aren’t familiar with what the SOLID principles are, check out Part 1, where we intro SOLID and discuss the Single Responsibility Principle, and Part 2 where we talk about the Open/Closed principle.
Liskov substitution principle for android#
This is part 3 of the SOLID Principles for Android Developers series.
