Ashwin Rao wrote:Should that subclass compulsorily pass the IS-A test or can I just use inheritance to avoid typing the same code again?
My reasoning: The opportunity for reusing code far exceeds the opportunity for implementing an "IS-A" relationship.
Had the designers of the Stack class remembered that, they could have designed this sort of class:-There you are using only the functionality of the Vector class which you actually need. Things like size() addElementAt(int) and elementAt(int) are not relevant to stacks, so they are hidden. So you can reuse a Vector object to make something new, and you have a fully‑functional stack class in 40‑something lines.
Favour composition over inheritance
Agree. When we started we were taught all about inheritance and how useful it is, but it is only later that you realise many things don't fit inheritance at all well and need a different approach.
Winston Gutkowski wrote: . . . but there are actually very few hierarchies that fit naturally into that style - particularly as Java only allows single inheritance. . . .
Are you sure it is yes‑yes? The example with Animal→Dog looks more like yes‑no.
Winston Gutkowski wrote: . . .
1. Is every instance of the right-hand class an instance of the left-hand one? 2. Can an instance of the right-hand class ever exist without an instance of the left-hand one?If the answer to both those questions is "yes", . . .
Ashwin Rao wrote:Let's say we have two (unrelated) classes A and B that use the same code. To reuse code I create a common parent class C and use inheritance to save myself from typing. But wouldn't that create class hierarchies that are possibly incorrect?
Campbell Ritchie wrote:Are you sure it is yes‑yes? The example with Animal→Dog looks more like yes‑no.
Does an instance of the right side always require an instance of the left side?
Ashwin Rao wrote:I think I'm finally starting to understand. Thanks for your help!
my overalls have superpowers - they repel people who think fashion is important. Tiny ad:
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earthhttps://coderanch.com/t/751654/free-earth-friendly-heat-kickstarter