| Author |
has-a and is-a (inheritance)
|
Ryan Tracy
Greenhorn
Joined: Mar 21, 2001
Posts: 9
|
|
Can someone explain in detail what has-a and is-a in inheritance is? I am trying add to a class some functionality from another class and a co-worker said to me,
There is a difference between a class that HAS and one that IS.
|
 |
Greg Charles
Bartender
Joined: Oct 01, 2001
Posts: 2538
|
|
|
"is a" and "has a" distinguish inheritance from delegation. For example, let's say you want a Vector that only allows objects of type Animal to be added to it. You have a choice of extendig java.util.Vector and overriding the methods to make that restriction. That's "is a". On the other hand, you could make a class that contained a Vector as a member variable. Your methods could mimic the interface of Vector, and delegate the work to the Vector member. That's "has a". Each approach has pros and cons. The GOF Patterns book is a good reference for this issue.
|
 |
Ryan Tracy
Greenhorn
Joined: Mar 21, 2001
Posts: 9
|
|
|
Anyone have another example or explanation?
|
 |
Marilyn de Queiroz
Sheriff
Joined: Jul 22, 2000
Posts: 9033
|
|
A Car "is-a" Vehicle. A Vehicle "has-a" Motor. A Car "is-a" Vehicle. A Car "has-a" Motor. A Bicycle "is-a" Vehicle. A Bicycle does not have a Motor.
|
JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
|
 |
Matthew Phillips
Ranch Hand
Joined: Mar 09, 2001
Posts: 2676
|
|
Here is the code that someone showed me to explain it. All vehicles have a motor so the vehicle has a member variable of type motor. A Car is a specialized type of vehicle because it inherits from vehicle. Since the Motor in Vehicle is protected Car can access this. A Car also has a Trunk and a Tire.
|
Matthew Phillips
|
 |
Greg Charles
Bartender
Joined: Oct 01, 2001
Posts: 2538
|
|
Ouch!
|
 |
Matthew Phillips
Ranch Hand
Joined: Mar 09, 2001
Posts: 2676
|
|
Originally posted by Greg Charles: Ouch!
???
|
 |
 |
|
|
subject: has-a and is-a (inheritance)
|
|
|