I have been learning java for the past two days and i have gotten confused with composition. what exactly is the point in composition and what does it do?Please leave some examples as well.
-
1possible duplicate of [Difference between Inheritance and Composition](http://stackoverflow.com/questions/2399544/difference-between-inheritance-and-composition) – MarsAtomic Sep 15 '14 at 18:13
-
[https://www.google.it/search?q=java+composition](https://www.google.it/search?q=java+composition) Look at the very first result – BackSlash Sep 15 '14 at 18:13
-
http://en.wikipedia.org/wiki/Object_composition – Henry Sep 15 '14 at 18:13
-
4Welcome to Stack Overflow, a site where you can obtain assistance with specific programming questions (as opposed to seeking help with tutorial information or as a substitute for due diligence (e.g. Google search). Please consult the Stack Overflow [help file](http://stackoverflow.com/help) for more information. – MarsAtomic Sep 15 '14 at 18:14
-
General learning tip: two days is not very much time. When I come across a topic like this that I just don't get, I find it's often helpful to make a note of it (I have an evernote just for these sorts of things) and move on. Regularly revisit your "things I don't get" notes, and try to resolve them. You may find the concepts are a lot easier with some more experience under your belt. For instance, once you've created a few classes, composition will probably seem a lot less abstract and a lot more obvious. – yshavit Sep 15 '14 at 18:33
1 Answers
I think it is already answered in so many links. Refer these links.
Implementation difference between Aggregation and Composition in Java, Favor composition over inheritance https://softwareengineering.stackexchange.com/questions/176049/what-is-the-use-of-association-aggregation-and-composition-encapsulation-in-c
Also read this link http://www.journaldev.com/1325/what-is-composition-in-java-java-composition-example
I put what Chandra posted. This might be what you are looking for
I think this is one of the most discussed point in Object Oriented design. As suggested in the article, composition is always preferred over inheritance. That doesn't mean that you should never use inheritance. You should where it makes more sense (which can debatable).
There are many advantages of using composition, couple of them are :
- You will have full control of your implementations. i.e., you can expose only the methods you intend to expose.
- any changes in the super class can be shielded by modifying only in your class. Any clients classes which uses your classes, need not make modifications.
- Allows you to control when you want to load the super class (lazy loading)