I read a summary which always use the definition "principle of substitution" when it talk about inheritance. But It doesn't explain the meaning of this principle.
What is this principle?
Thank you.
It means plainly: a subclass must honor the contract set by the super class.
If you extend a super class, you should read its document and implement as it dictates. That's all.
If I hear one more time "Liskov substitution" I'm going to kill a kitten.
You probably know it, just not by this name.
http://en.wikipedia.org/wiki/Liskov_substitution_principle
It just says "If S is a T, then references to T can be changed to references to S."
Basically says that a class that implements a determined interface can be replaced by any other implementing the same inteface. You can found more information about this in Liskov's Substitution Principle quoting the definition:
"If a program module is using the reference of a Base class, then it should be able to replace the Base class with a Derived class without affecting the functioning of the program module. "
Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it
it is also known as the liskov substitution
The principle of substitution or Liskov Substitution Principle (LSP) basically states that an object should only be in a hierarchy if in every scenario that object can be used as its parent. For a concrete example:
public class Rectangle {
//Stuff about rectangles }
public class Square extends Rectangle {
//VIOLATES LSP!!
}
public abstract class Shape
{
//stuff about shapes
}
public class Square extends Shape
{
//Square
}
public class Rectangle extends Shape
{
//Rectangle
}