• Post Reply Bookmark Topic Watch Topic
  • New Topic

Interview Qustion: What is preferred composition over Inheritance?  RSS feed

 
Atul Sawant
Ranch Hand
Posts: 304
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ranchers...

What is preferred composition over inheritance. Does it mean delegation? or is it something more than that?
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Choosing composition over inheritance is a general design principle. One place to start reading is the topic Choosing composition vs. inheritance from Thinking in Java, and then Composition vs. inheritance revisited (later in the same chapter)...
If you must upcast, then inheritance is necessary, but if you don�t need to upcast, then you should look closely at whether you need inheritance.

[ June 10, 2007: Message edited by: marc weber ]
 
Atul Sawant
Ranch Hand
Posts: 304
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Marc....nice to see your reply!

Thanks for your reply and links!

I saw the link and it gave a nice example of car class for displaying the use of composition..

Could you please provide an example of where there is an necessity of upcasting and hence introducing inherintance. I think i am getting it but just lost somewhere! ...

darn!
[ June 10, 2007: Message edited by: Atul Sawant ]
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Atul Sawant:
...Could you please provide an example of where there is an necessity of upcasting...

See the topic Extensibility (from the chapter following the one I referenced above). This starts describing the benefits of upcasting and polymorphism.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!