Click here to Skip to main content
12,953,652 members (51,878 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


1 bookmarked
Posted 23 Jul 2012

Liskov substitution principle (LSP)

, 23 Jul 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
Liskov substitution principle (LSP)

SOLID principles:

Use inheritance when you want to alter the behavior implemented by the non-abstract class. Use inheritance when you want to define the behavior not implemented, but specified by the abstract class. Implement interface when your class conforms to that interface. There are no other cases when you should want to do it. In other words, when you use extends/implements the interface/protocol should remain the same.

Let's consider an example:

(not for production, illustrative purposes only)

// there's a standard class ArrayList<t> in Java

public class MyList<T> extends ArrayList<T> {
  public void dumpFancily() {
    System.out.printf("I have %d items and here they are:\n", size());
    for(T item : this) {
      System.out.printf("I have %s\n", item);

The only aim of MyList is just to add a convenient method dumpFancily(). This convenience will only remain as long as your references to the objects of this class have a type of MyList. As soon as you use something like Collections.unmodifiableList() against your MyList, you'll lose your dumpFancily(), since unmodifiableList() returns List<T>:

MyList<Integer> myList = new MyList<integer>();
myList.dumpFancily(); // OK, you rock

// ERROR, won't compile
MyList<Integer> myReadonlyList = Collections.unmodifiableList(myList); 
// ERROR, won't compile

So, what's the big idea of your MyList<T> if you can't work with the standard library?


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer (Senior)
Russian Federation Russian Federation
No Biography provided

You may also be interested in...

Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170525.1 | Last Updated 23 Jul 2012
Article Copyright 2012 by loki2302
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid