What is the difference between Composition and Association relationship?

前端 未结 8 1980
眼角桃花
眼角桃花 2020-12-01 04:05

In OOP, what is the difference between composition (denoted by filled diamond in UML) and association (denoted by empty diamond in UML) relationship between classes. I\'m a

8条回答
  •  臣服心动
    2020-12-01 04:35

    I believe that a code-based example can help to illustrate the concepts given by the above responses.

    import java.util.ArrayList;
    
    public final class AssoCia
    {
        public static void main( String args[] )
        {
            B b = new B();
            ArrayList cs = new ArrayList();
    
            A a = new A( b, cs );
    
            a.addC( new C() );
            a.addC( new C() );
            a.addC( new C() );
            a.listC();
        }
    }
    
    class A
    {
        // Association -
        // this instance has a object of other class
        // as a member of the class.
        private B b;
    
        // Association/Aggregation -
        // this instance has a collection of objects
        // of other class and this collection is a
        // member of this class
        private ArrayList cs;
    
        private D d;
    
        public A(B b, ArrayList cs)
        {
            // Association
            this.b = b;
    
            // Association/Aggregation
            this.cs = cs;
    
            // Association/Composition -
            // this instance is responsible for creating
            // the instance of the object of the
            // other class. Therefore, when this instance 
            // is liberated from the memory, the object of
            // the other class is liberated, too.
            this.d = new D();
        }
    
        // Dependency -
        // only this method needs the object
        // of the other class.
        public void addC( C c )
        {
            cs.add( c );
        }
    
        public void listC()
        {
            for ( C c : cs )
            {
                System.out.println( c );
            }
        }
    
    }
    
    class B {}
    
    class C {}
    
    class D {}
    

提交回复
热议问题