Aggregation vs. composition

Discussion in 'Java' started by Rick Osborn, Jan 23, 2004.

  1. Rick Osborn

    Rick Osborn Guest

    I got asked at an interview lately if I knew the difference between
    aggregation and composition. We were discussing possible changes to
    a struts application, and how I would modify the code. He then made the
    parallel to A vs C. If I would deisn go to either paradigm.

    Not knowing this off the top of my head, he and the team looked
    at me in disgust and walked me out.

    I looked this up when I got home, and could do this in design
    discussions, or over iterative revisions. But at moment, off the top
    of my head?

    Am I missing the boat, or were they setting the bar a tad high?
    Rick Osborn, Jan 23, 2004
    #1
    1. Advertising

  2. Rick Osborn

    Sudsy Guest

    Rick Osborn wrote:
    > I got asked at an interview lately if I knew the difference between
    > aggregation and composition. We were discussing possible changes to
    > a struts application, and how I would modify the code. He then made the
    > parallel to A vs C. If I would deisn go to either paradigm.
    >
    > Not knowing this off the top of my head, he and the team looked
    > at me in disgust and walked me out.


    Sounds like the one about "which pattern would you choose in
    this scenario?"
    It also sounds like a bunch of people so wedded to buzzwords
    that you (or at least I) wouldn't be happy there anyway.
    Give me a real problem, along with a few minutes to consider
    the possibilities, and I'll tell you what approach I'd use.
    Ask me to name a pattern from a book? Please!
    As to this particular question, I'm not sure that I know the
    definition of either off the top of my head. Isn't an essay
    a form of composition? Or a symphony? Isn't an aggregate
    something you use to make concrete?
    Just for laughs, enter the following string into your favorite
    search engine:
    +aggregate +concrete +composition
    Kind of puts a different spin on things, eh?
    Sudsy, Jan 23, 2004
    #2
    1. Advertising

  3. Rick Osborn

    Sudsy Guest

    Rick Osborn wrote:
    > Am I missing the boat, or were they setting the bar a tad high?


    Postscript:
    Check out the definitions here:
    <http://www.bletchleypark.net/algorithms/software/oop.html>
    Think maybe the crew was, like, totally into UML!
    Sudsy, Jan 23, 2004
    #3
  4. Rick Osborn

    Marc Dzaebel Guest

    "Rick Osborn" <> schrieb im Newsbeitrag
    news:...
    >... he and the team looked at me in disgust and walked me out.
    > ... Am I missing the boat, or were they setting the bar a tad high?


    I don't know the exact conditions of the interview, however, IT is too
    complex to know everything. UML is getting a standard so the question is
    rather a basic one if the team works e.g. on web architectures. I'd guess
    the most IT experts don't know it and this kind of "knowledge" is certainly
    not the only think. The team shows at least a human evidence of incapacity.
    Marc Dzaebel, Jan 23, 2004
    #4
  5. Rick Osborn

    Ike Guest

    I agree with sudsy, it's pure nomenclature, and wont solve real problems,
    which, to me anyways, there is never a shortage of. However, in answer to
    your question, this should help:


    Composition
    Writing a class that contains objects as other members, like 'Birthday'
    which is a Date object, say, in class Employee.

    Composition and Inheritiance imply different relationships:

    Composition - One class has another class.

    Aggregation - One class is a kind of another class.

    Oftentimes, it is not so clear cut.



    -Ike
    Ike, Jan 23, 2004
    #5
  6. Ike wrote:

    > I agree with sudsy, it's pure nomenclature, and wont solve real problems,


    Having a common nomenclature *does* make solving problems easier.

    > Composition
    > Writing a class that contains objects as other members, like 'Birthday'
    > which is a Date object, say, in class Employee.
    >
    > Composition and Inheritiance imply different relationships:
    >
    > Composition - One class has another class.
    >
    > Aggregation - One class is a kind of another class.


    Aggregation has NOTHING to do with inheritance! In fact, Composition
    is merely a special case of aggregation in which the life cycle of
    the "part" is controlled by the whole.

    This difference is indeed quite academic, and using it as the deciding
    question in an interview indicates that the interviewer has wrong
    priorities.
    Michael Borgwardt, Jan 23, 2004
    #6
  7. Rick Osborn

    Marc Dzaebel Guest

    I completely agree with your comments. However, Rick already "looked it up"
    so *he* don't need an explanation ;-)
    Marc Dzaebel, Jan 23, 2004
    #7
  8. Rick Osborn

    Rick Osborn Guest

    No, I'd say you're all basically in line with what I was thinking.
    In my nearly 8 yrs (it sounds some of you even more) yes, I got home and
    found the "answer" in my trusty UML Distilled book.

    But thanks to you all, you did confirm my suspicions. These guys
    are focused my on terms than solutions.




    Michael Borgwardt <> wrote in message news:<bur4pg$l3jhd$-berlin.de>...
    > Ike wrote:
    >
    > > I agree with sudsy, it's pure nomenclature, and wont solve real problems,

    >
    > Having a common nomenclature *does* make solving problems easier.
    >
    > > Composition
    > > Writing a class that contains objects as other members, like 'Birthday'
    > > which is a Date object, say, in class Employee.
    > >
    > > Composition and Inheritiance imply different relationships:
    > >
    > > Composition - One class has another class.
    > >
    > > Aggregation - One class is a kind of another class.

    >
    > Aggregation has NOTHING to do with inheritance! In fact, Composition
    > is merely a special case of aggregation in which the life cycle of
    > the "part" is controlled by the whole.
    >
    > This difference is indeed quite academic, and using it as the deciding
    > question in an interview indicates that the interviewer has wrong
    > priorities.
    Rick Osborn, Jan 26, 2004
    #8
  9. Rick Osborn

    BarryNL Guest

    Rick Osborn wrote:
    > I got asked at an interview lately if I knew the difference between
    > aggregation and composition. We were discussing possible changes to
    > a struts application, and how I would modify the code. He then made the
    > parallel to A vs C. If I would deisn go to either paradigm.
    >
    > Not knowing this off the top of my head, he and the team looked
    > at me in disgust and walked me out.
    >
    > I looked this up when I got home, and could do this in design
    > discussions, or over iterative revisions. But at moment, off the top
    > of my head?
    >
    > Am I missing the boat, or were they setting the bar a tad high?


    Well, it depends what you said you knew before the interview. If you
    told them you knew UML, for example, then you should certainly be able
    to explain the difference between Agg. & Comp. It's not really standard
    Java stuff though. In Java Agg., Comp. and normal 1-M assocs would
    probably all be implemented as a Vector or ArrayList, for example.
    BarryNL, Jan 26, 2004
    #9
  10. Rick Osborn

    BarryNL Guest

    Ike wrote:
    > I agree with sudsy, it's pure nomenclature, and wont solve real problems,
    > which, to me anyways, there is never a shortage of. However, in answer to
    > your question, this should help:
    >
    >
    > Composition
    > Writing a class that contains objects as other members, like 'Birthday'
    > which is a Date object, say, in class Employee.
    >
    > Composition and Inheritiance imply different relationships:
    >
    > Composition - One class has another class.
    >
    > Aggregation - One class is a kind of another class.


    Composition indicates that the child objects are conceptually a part of
    the parent and make no sense on their own. A typical example might be
    objects 'Invoice' and 'InvoiceLines', where invoice lines are clearly a
    part of an invoice and would never exist without being part of (and thus
    linked to) an invoice. Composition indicates that the child objects are
    wholly dependent on the parent for their existance and indicate to a
    developer that they should code the parent in such a way that, for
    example, if the parent is deleted it ensures all children are also deleted.

    Composition is far more strict than a simple 'HASA' relationship.
    BarryNL, Jan 26, 2004
    #10
  11. Rick Osborn

    nos Guest

    "BarryNL" <> wrote in message
    news:4014f175$0$318$4all.nl...
    > Rick Osborn wrote:
    > > I got asked at an interview lately if I knew the difference between
    > > aggregation and composition. We were discussing possible changes to
    > > a struts application, and how I would modify the code. He then made the
    > > parallel to A vs C. If I would deisn go to either paradigm.
    > >
    > > Not knowing this off the top of my head, he and the team looked
    > > at me in disgust and walked me out.
    > >
    > > I looked this up when I got home, and could do this in design
    > > discussions, or over iterative revisions. But at moment, off the top
    > > of my head?
    > >
    > > Am I missing the boat, or were they setting the bar a tad high?

    >
    > Well, it depends what you said you knew before the interview. If you
    > told them you knew UML, for example, then you should certainly be able
    > to explain the difference between Agg. & Comp. It's not really standard
    > Java stuff though. In Java Agg., Comp. and normal 1-M assocs would
    > probably all be implemented as a Vector or ArrayList, for example.


    --
    sun tutorial has aggregation and composition here

    http://onesearch.sun.com/ClickThru?qt=aggregation&url=http://developer
    s.sun.com%2Fevents%2Ftechdays%2Fpresentations%2Fseattle%2FJ2EEandAdvancedFea
    tures.pdf&pathInfo=%2Fsearch%2Fdevelopers%2Findex.jsp&hitNum=8&col=javatecha
    rticles&col=javatutorials&col=devall&col=devarchive&col=javadoc
    nos, Jan 26, 2004
    #11
  12. Rick Osborn

    amitg_amity

    Joined:
    Aug 30, 2009
    Messages:
    1
    Composition - has a relationship - one class has another class's object which is created itself inside the class method, constructor, or as a instance of that class.
    Ex.
    Code:
     
    class A{ }
    class B {  //class B has A.
        A a=new A(); /* this is composition. [COLOR=red]A[/COLOR] has no  
                            life after [COLOR=red]B[/COLOR] class's instance is 
                           set to null(Of course you have to create [COLOR=red]B[/COLOR] class's 
                           instance first.) */
    }
    Aggregation - has a relationship(same as composition but with little difference) - one class has another class's object but through pass by value of reference of object.
    Ex.
    Code:
    class A{ }
    class B{
    A a=null; // class B has A.
    B(A a){ // this is aggregation. Object [COLOR=red]A[/COLOR] can have a life even after 
    // [COLOR=red]B[/COLOR] class's instance is set to null. ( of course here also you 
    // have to create [COLOR=red]B[/COLOR] class's instance first )
    this.a = a;
    }
    public String getObject(A a){ // this is aggregation. 
    return a.toString();
    }
    }
     
    ============End Aggregation=============================
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.HashMap;
    public class Test {
     static BufferedWriter bw=null;
     static StringBuffer sb=new StringBuffer();
     private static ArrayList<String> array=new ArrayList<String>(); //testing
     
     public static void main(String[] args) {
      try {
       bw = new BufferedWriter(new FileWriter((new Long(new Date().getTime()).toString())));
       String path = "p1//InformationTechnologyEmployee.java";
       method(path);
       for(int i=0;i<array.size();i++){
        
       }
      } catch (IOException e) {
       e.printStackTrace();
      }finally{
       try {
        bw.write(sb.toString());
        bw.close();
       } catch (IOException e) {
        e.printStackTrace();
       }
      }
     }
     private static void method(String path) {
      if (path != null || path.length() > 0) {
       try {
        BufferedReader br = new BufferedReader(new FileReader(path));
        String eachLineReadInFile = null;
        ArrayList<String> arrayListOfInstanceVariable = new ArrayList<String>();
        HashMap<String,String> hmClassNameWithClassPath = new HashMap<String,String>(); // [class name=key] & [class path=value] 
        while ((eachLineReadInFile = br.readLine()) != null) {
         String previousLine = new String(eachLineReadInFile);
         String newline = new String(eachLineReadInFile.replaceAll("package|return|import|this|[{]|[}]|[/]|
    [*]|final", ""));
         if (eachLineReadInFile.indexOf("import") > -1) {
          String filteredClassName = eachLineReadInFile.substring(eachLineReadInFile.lastIndexOf(".") + 1, eachLineReadInFile.length() - 1);
          String filteredClassPath = eachLineReadInFile.replaceAll("import|[;]","").replaceAll("[.]", "//").trim();
          hmClassNameWithClassPath.put(filteredClassName, filteredClassPath);
         }
         if (!newline.equals(eachLineReadInFile))
          continue;
         System.out.println(previousLine);
         if (previousLine.trim().replaceAll("[;]", "").length() != 0){
          String instanceVariable = previousLine.trim().replaceAll("[;]|public|static|protected|private","");
          arrayListOfInstanceVariable.add(instanceVariable.trim());
         }
        }
        System.out.println(arrayListOfInstanceVariable);
        String classs = path.substring(path.lastIndexOf("//")+2,path.lastIndexOf("."));
        String classReference = Character.toLowerCase(classs.charAt(0))+classs.substring(1);
        String createNewInstance = classs+" "+classReference+" = new "+classs+"();\r";
        array.add(classs.toLowerCase());
        sb.insert(0,createNewInstance);
        for (int nextInstance = 0; nextInstance < arrayListOfInstanceVariable.size(); nextInstance++) {
         String previousDataTypeOfInstanceVariable = (String) arrayListOfInstanceVariable.get(nextInstance);
         String newDataTypeOfInstanceVariable = new String(previousDataTypeOfInstanceVariable.replaceAll(
           "int|float|byte|long|String|boolean|double", ""));
         String methodName = Character.toUpperCase(previousDataTypeOfInstanceVariable.split(" ")[1].charAt(0))+previousDataTypeOfInstanceVariable.split(" ")[1].substring(1);
         if (newDataTypeOfInstanceVariable.equals(previousDataTypeOfInstanceVariable)) {
          String className = newDataTypeOfInstanceVariable.split(" ")[0];
          String passingReference = Character.toLowerCase(previousDataTypeOfInstanceVariable.split(" ")[0].charAt(0))+previousDataTypeOfInstanceVariable.split(" ")[0].substring(1);
          sb.append(classReference+".set"+methodName+"("+passingReference+");\r");
          if(className.indexOf("List")>-1){
           System.out.println("className before "+className);
           className = className.split("[<]|[>]")[1];
          }
          if(!hmClassNameWithClassPath.containsKey(className)){
           String pathForSamePackageVariable=path.substring(0,path.lastIndexOf("//")+2)+className;
           hmClassNameWithClassPath.put(className,pathForSamePackageVariable);
          }
          String instanceRef = (String) hmClassNameWithClassPath.get(className);
          method(instanceRef + ".java");
         }else{
          if(previousDataTypeOfInstanceVariable.indexOf("String")>-1){
           passArgument(classReference, createNewInstance, methodName,"(null)"); 
          }else{
           if(previousDataTypeOfInstanceVariable.indexOf("boolean")>-1){
            passArgument(classReference, createNewInstance, methodName,"(false)");        
           }else{
            passArgument(classReference, createNewInstance, methodName,"(0)");
           }
          }
         }
        }
       } catch (Exception e1) {
        e1.printStackTrace();
       }
      } else {
       return;
      }
     }
     private static void passArgument(String classReference, String createNewInstance, String methodName, String argument) {
      sb.insert(createNewInstance.length(),classReference+".set"+methodName+argument+";\r");
     }
    }
    
    
    Last edited: Nov 6, 2009
    amitg_amity, Aug 31, 2009
    #12
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Markos Charatzas

    Interfaces and aggregation

    Markos Charatzas, Jan 30, 2004, in forum: Java
    Replies:
    7
    Views:
    1,937
    BarryNL
    Feb 2, 2004
  2. Chris K
    Replies:
    1
    Views:
    566
    Victor Bazarov
    Apr 17, 2004
  3. Gary Wessle

    aggregation vs. composition

    Gary Wessle, Nov 26, 2006, in forum: C++
    Replies:
    2
    Views:
    547
    Daniel T.
    Nov 26, 2006
  4. Salman
    Replies:
    4
    Views:
    866
    John Harrison
    Feb 21, 2007
  5. David B.
    Replies:
    6
    Views:
    136
    Panda Beer
    Jan 6, 2009
Loading...

Share This Page