File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Composition and Inheritance

 
Mathews P Srampikal
Ranch Hand
Posts: 211
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the difference between Composition and Inheritance in java.
Thanks.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Java, or in any language, inheritance is, well, inheritance -- as expressed by the "extends" keyword; while composition refers to the inclusion of one object inside another as a member.
In this example, Bar gets access to Foo's capabilites via inheritance:

While here it gets them via composition:

The general, oversimplified rule is to use composition when you can, inheritance when you must.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic