Click here to Skip to main content
12,399,640 members (51,335 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

6.7K views
1 bookmarked
Posted

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.add(123);
myList.dumpFancily(); // OK, you rock

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

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

License

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

Share

About the Author

loki2302
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 --
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160721.1 | Last Updated 23 Jul 2012
Article Copyright 2012 by loki2302
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid