# Substitution principle ( is a vs is like a relationship )

• September 12th, 2012, 10:49 AM
thesoulpatchofBruce
Substitution principle ( is a vs is like a relationship )
Hey guys
I still pretty new to Java and how it works.
I am think I am getting the hang of how Inheritance is working
except this idea of the substitution principle and the is like a relationship
Can anybody explain this preferably with some code so I can understand !

Thanks
• September 12th, 2012, 04:30 PM
helloworld922
Re: Substitution principle ( is a vs is like a relationship )
The substitution principle means just that: you can substitute in a class with another one which inherits from that class. When you inherit a class you should be able to do a drop-in replacement without any other changes. (Basically a restatement of the Liskov substitution principle). Anything which violates this is considered a "is like a" relationship.

This Wikipedia article provides an interesting example:

A square is like a rectangle. They both have 4 sides and 4 right angles. It may even make sense for a square class to extend a rectangle class since all squares mathematically are rectangles. However, this violates the the Liskov substitution principle because a square must have all sides of the same length while a rectangle has a width and height. It's reasonable to assume a rectangle class would have a setWidth() and setHeight() methods which can set each field separately. However, these methods don't make much sense for squares. You might alter the setWidth() and setHeight() methods to set the side length instead, but this alters the fundamental principle of how these methods are suppose to work: they set the width and height differently. So this would break code that looks like this:

Code Java:

```Rectangle a = new Square(); a.setWidth(5); a.setHeight(3); System.out.println("Area of a is " + a.getArea()); // should be 15, but here it possibly 9 or undetermined```
• September 27th, 2012, 03:52 PM
thesoulpatchofBruce
Re: Substitution principle ( is a vs is like a relationship )
Hey sorry for the late reply I think I get it now thanks :)