Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regarding inheritance and composition

 
santhosh kumar vk
Ranch Hand
Posts: 152
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,

I have one doubt that is, what is inheritance and what is composition and when should use inheritance and composition, can you tell me how to make composition please help me.


Thanking You.
 
Lee Kian Giap
Ranch Hand
Posts: 213
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well , I am not going to explain inheritance and composition , thousand of book have explain it with great example , one of the book is "Thinking In Java".

The thing to take note is , when considering reuse, think of composition over inheritance.


 
Michael Angstadt
Ranch Hand
Posts: 277
Eclipse IDE Java PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Without composition:


With composition:


Without inheritance:


With inheritance:
 
Istvan Kovacs
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Michael Angstadt wrote:Without composition:


With composition:



No, not quite. Composition involves delegating to another type; by delegating to a number of different objects you achieve something similar to multiple inheritance. A simple case:
1. define interface for supertype
2. define interface for subtype, extending interface of supertype
3. implement supertype interface with a class
4. implement subtype interface with a class, without extending superclass; instantiate superclass and deleget superinterface methods to the instance.

 
Danish Sualeh
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could refer to The Strategy Pattern to help appreciate the advantage of composition over inheritance.

It will sure give you a better understanding of when to choose composition or inheritance
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic