wood burning stoves*
The moose likes Java in General and the fly likes Inheritance Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Inheritance" Watch "Inheritance" New topic
Author

Inheritance

Md Asif S Sayeed
Greenhorn

Joined: Oct 20, 2009
Posts: 2
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

Joined: Mar 04, 2009
Posts: 417
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

Joined: Mar 24, 2008
Posts: 3826

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.

SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Inheritance