s ravi chandran wrote:it will show why we shd be using inheritance...
s ravi chandran wrote:k, the question put up was, if I have to use A in B, what will be more efficient, ...
ergo the first answer (where B does not inherit from A, but instead uses an A) is better (if it is not given that B IS-An A).Paul Clapham wrote:
s ravi chandran wrote:it will show why we shd be using inheritance...
Reusing code is not a good reason to use inheritance. ...
s ravi chandran wrote:well, I had told that B inheriting A would give B a chance to specialize A's methods. but the interview did not take that answer.. I was just stuck up.. not knowing what else to say..
Junilu Lacar wrote:
s ravi chandran wrote:well, I had told that B inheriting A would give B a chance to specialize A's methods. but the interview did not take that answer.. I was just stuck up.. not knowing what else to say..
Sometimes, the interviewer is not looking for a direct answer but rather the kind of replies given here. If you had argued along the lines that Bear, Jesper and others did, a good interviewer would probably have been impressed. On the other hand, if the interviewer was looking for something other than these, and had you given an answer that satisfied him, and he gave you the job and you would actually work for/with that guy... well, consider yourself lucky that you got stuck on the question.
On second thought, the interviewer might have been fishing for your knowledge of the advice to "Prefer composition over inheritance" -- I would say that's just a rule of thumb. Given that the class names A and B are not particularly useful, I would still argue along the lines that Bear and Jesper drew earlier.
sandy sean wrote:Generally Composition (HAS-A) is preffered over Inheritence (IS-A) if it is considered only for code resuse but it actually depends on the relation between the two classes.
Suppose your A is Vehicle class and B is Car class, then Car IS-A Vehicle so here inheritence comes into play.
class Car extends Vehicle{
}
But suppose A is Car class and B is Wheel class, then there is not a is-a relationship between Car and Wheel classes. we can't say Wheel IS-A Car but we can say Car HAS-A Wheel.
So there is Has-a relationship between them. Here Composition will be preffered over inheritence.
class Car{
Wheel wheelObj;
...
}
THAT WAS GOOD EXPLANATION WITH EXAMPLE.
THANKS