The Liskov substitution principle states that if we are using hierarchies and using a base class, we must extend it without replacing the functionality of old classes.

Derived types must be completely replaceable by their base types.

Consider the following example using a Square that extends the behavior of a Rectangle:

class Rectangle {
	protected width;
	protected height;

	public void setWidth(int width) {
		this.width = width;
	}

	public void setHeight(int height) {
		this.height = height;
	}

	public int getWidth() {
		return this.width;
	}

	public int getHeight() {
		return this.height;
	}

	public int getArea() {
		return this.width * this.height;
	}
}

class Square extends Rectangle {
	public void setWidth(int width) {
		this.width = width;
		this.height = width;
	}

	public void setHeight(int height) {
		this.width = height;
		this.height = height;

	}
}

class ApplicationTest
{
	private static Rectangle getNewRectangle()
	{
		// can be returned by a factory 
		return new Square();
	}

	public static void main (String args[])
	{
		Rectangle r = ApplicationTest.getNewRectangle();
        
		r.setWidth(5);
		r.setHeight(10);
		// r is a rectangle? Can be a Square! 
		// the user assumes that it has the same behavior as the rectangle

		System.out.println(r.getArea());
		// Now the user is surprised, because the area is 100 (10 * 10) instead of 50 (10 * 5).
	}
}

The behavior of the Square extends the Rectangle, but the Square itself doesn’t need the width and height properties. Besides that, even if the Square respects his rules, it is not clean code extending it from the Rectangle since, we are expecting to change the width or height, not change both at the same time using a “supposed” Rectangle when at that time, the factory returned a Square.

A good solution in this case would be to create a more general interface or base class for the Rectangle and for the Square to split different behaviors.

Conclusion

You need to make sure that new derived classes are extending the base classes without changing their behavior. Maybe in this case we needed to create a new super type that was extended by the Rectangle and the Square.

Bibliography

http://www.oodesign.com/liskov-s-substitution-principle.html

http://en.wikipedia.org/wiki/Liskov_substitution_principle

http://www.objectmentor.com/resources/articles/lsp.pdf