aspose file tools*
The moose likes OO, Patterns, UML and Refactoring and the fly likes Inheritance or composition? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "Inheritance or composition?" Watch "Inheritance or composition?" New topic
Author

Inheritance or composition?

Bruce Jin
Ranch Hand

Joined: Sep 20, 2001
Posts: 671
Inheritance or composition?
All beginner Java books say that inheritance is such a good thing. But all oop/design books say on the first page: Favor composition over inheritance!
I guest there must be some guideline as where to use inheritance or composition. Can anybody give such guidelines or point to a good book for this?
Thanks!


BJ - SCJP and SCWCD
We love Java programming. It is contagious, very cool, and lot of fun. - Peter Coad, Java Design

Crazy Bikes created by m-Power
Jeremy Thornton
Ranch Hand

Joined: Feb 21, 2002
Posts: 91
I think that most books on OO cover this aspect in quite a lot of detail.
In general, ask yourself the question - does X have a Y or is X a Y (known as the hasA or isA relationship).
hasA is modelled using composition, isA by inheritance.
Favour composition.
Bruce Jin
Ranch Hand

Joined: Sep 20, 2001
Posts: 671
hasA is modelled using composition, isA by inheritance

HasA --> composition
isA --> inheritance
The distiction is clear. How can I favor one of them?
Jeremy Thornton
Ranch Hand

Joined: Feb 21, 2002
Posts: 91
The distinction is clear in english - not always so clear cut in design.
Inheritance is used for other things than intended in "pure" OO. e.g. if source code is locked for release, sometimes people inherit and extend to allow for new or altered features.
All I meant by favour was if in doubt give composition a go.
Bruce Jin
Ranch Hand

Joined: Sep 20, 2001
Posts: 671
Thanks.
Where will the doubt come from? Unless the situation can not be discribed by isA or hasA otherwise it is always clear.
[ September 23, 2002: Message edited by: Bruce Jin ]
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 5019
    
    8

Bruce,
Joshua Bloch's book "Effective Java" has a lengthy discussion of favoring composition over inheritance.
You might also want to go over this article on OO Design Principles and Patterns and this article on the Liskov Substitution Principle, both by Robert Martin.
[ September 23, 2002: Message edited by: Junilu Lacar ]

Junilu - [How to Ask Questions] [How to Answer Questions]
Bruce Jin
Ranch Hand

Joined: Sep 20, 2001
Posts: 671
Thanks Julinu!
I downloaded the 2 papers and will take a look of Bloch's book.
I am reading Peter Coad's Java Design. It seems a good book. Does anybody have comments about this book?
Thanks.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Bruce Jin:
Where will the doubt come from? Unless the situation can not be discribed by isA or hasA otherwise it is always clear.

Unfortunately (?), isA relationships from the model don't always translate into "isA" relationships in the code. http://c2.com/cgi/wiki?CircleAndEllipseProblem discusses one of the most popular examples.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 5019
    
    8

Bruce,
I thought that first article by Robert Martin had something about composition vs. inheritance but I couldn't find it. It must have been in another document. It's still a good article though. The one about LSP discusses proper/improper use of inheritance (uses C++ examples but it shouldn't be too hard to follow the discussion).
Bruce Jin
Ranch Hand

Joined: Sep 20, 2001
Posts: 671
Thanks.
The first article also mentions Liskov and has the Circle and Ellipse example.
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
See the URL "Some OO dessign principles" from Bob Tarr here very relevant !


SCJP2. Please Indent your code using UBB Code
Wilfried LAURENT
Ranch Hand

Joined: Jul 13, 2001
Posts: 269
"Inheritance vs Composition" is certainly one of the most discussed subject in object-oriented programming.
Simply type "Inheritance Composition" in any search engine to be convinced of that.
...and the winner is .... "Favor composition over inheritance" (Raw and uninterpreted result ).

W.
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
By the way in the URL I gave, the last reason for not chosing inheritance was:
If the class belongs to the Problem Domain inherit, against composition, only if the class was a device, transaction or role.
Dou you know why only these ones?
Bruce Jin
Ranch Hand

Joined: Sep 20, 2001
Posts: 671
Thank you all.
I downloaded all Bob Tarr's design pattern papers. One of them is OOP principles. Very interesting. Tarr use Coad's principle to decide when inheritance/composition should used.
Jon Kern
Greenhorn

Joined: Aug 05, 2004
Posts: 3
Coad's Java Design does have some very good pointers on when to consider composition vs inheritance and some simple guidelines. To quote our book...

Use inheritance when you can satisfy these criteria:
  • "Is a special kind of," not "is a role played by a"
  • Never needs to transmute to be an object in some other class
  • Extends rather than overrides or nullifies superclass
  • Does not subclass what is merely a utility class
  • Within the problem domain, expresses special kinds of roles, transactions, or things


  • In general, if you have any doubts, always choose composition :=)

    Some people make the horrid, abusive mistake of inheriting from a persistence class or a security class, all in an attempt to ensure all child classes have security and persistence. Puke.

    Add the behavior by "bolting on" the classes through inheritance.


    -- jon
    Bruce Jin
    Ranch Hand

    Joined: Sep 20, 2001
    Posts: 671
    Thanks Jon.
    I read Toad's book 2 years ago. I could find very few books about OOP in Java. His book was published 1998 I think. I wonder if there are any new books recently covering this topic.
    Ilja Preuss
    author
    Sheriff

    Joined: Jul 11, 2001
    Posts: 14112
    Originally posted by Jon Kern:
    Use inheritance when you can satisfy these criteria:
  • "Is a special kind of," not "is a role played by a"
  • Never needs to transmute to be an object in some other class
  • Extends rather than overrides or nullifies superclass
  • Does not subclass what is merely a utility class
  • Within the problem domain, expresses special kinds of roles, transactions, or things



  • I would add

  • Subclass can be used everwhere the superclass is used, without the client even noticing - that is, you have conformance to Liskov's Substitution Principle (notice that some classes from the JDK actually violate this principle!)

  • Stan James
    (instanceof Sidekick)
    Ranch Hand

    Joined: Jan 29, 2003
    Posts: 8791
    Lots of great comments! I'll just amplify the references to LSP. If you're dead serious about LSP it is very hard to extend a concrete class. It is also dangerous if you don't own and carefully control the parent class. Here's a Holub rant on Why Extends is Evil. It's his usual inflamatory extreme point of view so watch your blood pressure, but he has useful examples of fragile subclasses.

    Anybody else remember the APOL library in PowerBuilder? Their idea was to put every possible feature you could ever need in one superclass. Yipes!


    A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
    Nikhil Vasaikar
    Ranch Hand

    Joined: Aug 18, 2004
    Posts: 56
    Hi,

    I just thought of putting in my comments. I feel that with Inheritance you are restricting to a specific implementation. However with Object composition you are free to choose any implementation by simply using a Factory. This is the advantage of Object composition over Inheritance.

    Regards,

    Nikhil
    Bruce Jin
    Ranch Hand

    Joined: Sep 20, 2001
    Posts: 671
    Thanks Nikhil.
    Another important point is that inheritance breaks encapsulation, the foundation of OOP. My early coding using inheritance is still giving me trouble.
    But inheritance is very convenient to use and sometimes I am tempted to use it.
     
    It is sorta covered in the JavaRanch Style Guide.
     
    subject: Inheritance or composition?