Aggregation and Composition in Java Code

前端 未结 2 1417
猫巷女王i
猫巷女王i 2021-01-06 14:56

As the Aggregation and Composition is related Association or we can say it gives the understanding of relationship between object or anything else.

I posted this que

2条回答
  •  青春惊慌失措
    2021-01-06 15:27

    Consider a simple example of a LinkedList class. A LinkedList is made up of Nodes. Here LinkedList class is the owning object. When it is destroyed, all the Nodes contained in it are wiped off. If a Node object is deleted from the list, the LinkedList object will still exist.

    Composition is implemented such that an object contains another object.

    class LinkedList {
    
     Node head;
     int size; 
    }
    

    This is composition.

    Another example, consider a Circle class which has a Point class which is used to define the coordinates of its center. If the Circle is deleted its center is deleted along with it.

    class Circle {
    
        private float radius;
        private Point center;
    
        public Circle(Point center, float radius) {
            this.center = center;
            this.radius = radius;
        }
    
        public void setRadius(float radius) {
            this.radius = radius;
        }
    
        public void setCenter(Point center) {
            this.center = center;
        }
    
        public float getRadius() {
            return radius;
        }
    
        public Point getCenter() {
            return center;
        }
    
        class Point {
            private int x;
            private int y;
    
            public Point(int x, int y) {
                this.x = x;
                this.y = y;
    
            }
    
            public void setY(int y) {
                this.y = y;
            }
    
            public void setX(int x) {
                this.x = x;
            }
    
            public int getY() {
                return y;
            }
    
            public int getX() {
                return x;
            }
        }
    
        @Override
        public String toString() {
    
            return "Center: " + "(" + center.getX() + "," + center.getY() + ")" + "\nRadius: " + this.getRadius()
                    + " centimeters";
        }
    
    }
    

    Example of composition from java collections api : HashMap has an Entry class. If the HashMap object is deleted all the Entry objects contained in the map are deleted along with it.

    Aggregation is also a type of Object Composition but not as strong as Composition. It defines "HAS A" relationship. Put in very simple words if Class A has a reference of Class B and removing B doesn't affect the existence of A then it is aggregation. You must have used it at some point.

提交回复
热议问题