5.5 IS-A & HAS-A Relationships
In our final lesson within this section we investigate code that implements "is-a" and/or "has-a" relationships.
Lets take a look at the points outlined at the Oracle Website for this part of the certification.
- Section 5: OO Concepts
- Develop code that implements "is-a" and/or "has-a" relationships.
How do we know what to make a superclass or subclass and what goes into our instance variables for these classes. There is a very simple way to check, by using the
HAS-A test, to see what sort of relationships our classes and data members have. So how do we do this?
IS-A, anywhere where you would use the
extends keyword just replace it with
IS-A and see how the relationship looks.
HAS-A test, use the class followed by
HAS-A and then the name of the possible instance variable and see how the relationship looks.
Try the following test to get to grips with
|Hammer extends Toolbox||Hammer IS-A Toolbox - no.|
Hammer HAS-A Toolbox - no.
Toolbox IS-A Hammer - still no.
Toolbox HAS-A Hammer - yes.
|Car extends Vehicle||Car IS-A Vehicle - yes.|
Car HAS-A Vehicle - no.
|Sink extends Kitchen||Sink IS-A Kitchen - no.|
Sink HAS-A Kitchen - no.
Kitchen IS-A Sink - still no.
Kitchen HAS-A Sink - yes.
|Bird extends Canary||Bird IS-A Canary - no.|
Bird HAS-A Canary - no.
Canary IS-A Bird - yes.
Canary HAS-A Bird - no.
|Window extends House||Window IS-A House - no.|
Window HAS-A House - no.
House IS-A Window - still no.
House HAS-A Window - yes.
HAS-A are quite a simple way for checking inheritance relationships and the good thing is we can test for subclass suitability all the way down the inheritance tree.