• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inheritance

 
Md Asif S Sayeed
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi...
Please answer this,I was asked this in an interview....
Why do we extend a class when we can create an instance of it and use it any class we want???
 
Leandro Coutinho
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Md Asif S Sayeed wrote:Hi...
Please answer this,I was asked this in an interview....
Why do we extend a class when we can create an instance of it and use it any class we want???

This is a good question. :]
I have this doubt too. Like: should my class extend JFrame or have an instance of JFrame?
First the good sense. Suppose you have a class Car and a class Ferrari. It doesn't make sense have an instance of car in the Ferrari class.
Second for convenience. You don't have to create another instance all the time. (I think this is not a good excuse).
Third, and maybe the main reason, it's when you want to offer a different implementation of some method.

I think the great a thing about the IS-A relationship is polymorphism.

I'm not sure too. Let's see what others have to say.
 
Vijitha Kumara
Bartender
Pie
Posts: 3918
10
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Md Asif S Sayeed wrote:Please answer this,I was asked this in an interview....
Why do we extend a class when we can create an instance of it and use it any class we want???

You should extend a class when you have common behavior which you can reuse in other class(es). Of course composition is prefered over inheritence which avoid all the un-necessary methods being inherited so you can extend another class if you want. If you have common abstract class (with some common implementations) others can use that class, and it may not useful in its own (even not possible with abstract). And if you need custom implementaions on some methods while keeping some are intact it may be desirable to use inheritance.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic