KIO
Kreative Ideen online
Using IS-A and HAS-A

Using IS-A and HAS-A

Remember that when one class inherits from another, we say that the subclass extends the superclass. When you want to know if one thing should extend another, apply the IS-A test.

IS-A

“Triangle IS-A Shape” (would make sense to create a superclass “shape” and subclass “triangle” would inherit methods and instance variables)

“Cat IS-A Animal” (would make sense to create a superclass “shape” and subclass “triangle” would inherit methods and instance variables)

“Tub extends Bathroom”..sounds reasonable. Until you apply the IS-A test… “Tub IS-A Bathroom” doesnt fit.

Does it make sense to say type X IS-A type Y?
If it doesn’t, you know there’s something wrong with the design.

HAS-A

So if we apply the IS-A test, Tub IS-A Bathroom is definitely false. What if we reverse it to Bathroom extends Tub? That still doesn’t work. Tub and Bathroom are related, but not through inheritance. Tub and Bathroom are are joined by HAS-A relationship.
Does it make sense to say “Bathroom HAS-A Tub”?

If yes, then it means that Bathroom has a Tub instance variable. In ohter words, Bathroom has a reference to a Tub, but Bathroom does not extend Tub and vice-versa.

Leave a Reply

Your email address will not be published. Required fields are marked *