• Post Reply Bookmark Topic Watch Topic
  • New Topic

composition Vs inheritance  RSS feed

 
prabir kumar
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
please somebody tell me what is composition in core java...is it another name of HAS-A relationship? .......somebody help
 
Vijayya Bijoor
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
composition ex: If student is in a class then student cannot exist without a class. There exists composition between class and students.

Composition Vs aggregation(also called "Has-a" relationship)
A Library contains students and books. Relationship between library and student is aggregation. Relationship between library and book is composition. A student can exist without a library and therefore it is aggregation. A book cannot exist without a library and therefore its a composition. For easy understanding I am picking this example. Don’t go deeper into example and justify relationships!

-
 
Chan Ag
Rancher
Posts: 1090
14
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The english word 'composition' would mean what anything is made up of - or what it 'has'. Example Birds have wings ( at least most of them have wings.). We could represent this in java as-

So composition means Bird "has-a" Wings ( composition).

When we say inheritance, we mean inheriting ( english ) an attribute from a parent/parents's parent and so on..

Just like You "is-A" Human, or some IntelligentBird "is-A" Bird.

In java , this could be represented as



So now IntelligentBird "is-A" Bird that has Wings and can fly cause it 'is-A" Bird ( inheritance). But IntelligentBird also can storeFood() - specialization in java terms.

Hope that helps.
Chan.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
prabir kumar wrote:please somebody tell me what is composition in core java...is it another name of HAS-A relationship? .......somebody help

Basically: yes. And, as Chan showed, it's usually done by defining another type of object as a member.

Since Vijayya introduced it, "aggregation" is a looser form of composition in which the "contained" object can exist independently of its container - as in his example of a Library and a Book. Wings can't exist independently of a Bird though; so in some OO languages a Bird object might need to "clean up" its Wings when it is deleted.

In Java, this usually isn't an issue because you don't explicitly "delete" objects; however, there are rare (usually resource-hungry) cases, like File channels and database connections, where understanding the difference is important.

Winston
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!