{"id":4760,"date":"2024-11-12T21:31:01","date_gmt":"2024-11-12T16:31:01","guid":{"rendered":"https:\/\/afzalbadshah.com\/?p=4760"},"modified":"2025-08-05T06:57:12","modified_gmt":"2025-08-05T01:57:12","slug":"composition-and-aggregation-in-java","status":"publish","type":"post","link":"https:\/\/afzalbadshah.com\/index.php\/2024\/11\/12\/composition-and-aggregation-in-java\/","title":{"rendered":"Association, Composition and Aggregation in Java"},"content":{"rendered":"\n<p>In Java, <strong>Association<\/strong>, <strong>composition<\/strong>, and <strong>aggregation<\/strong> define relationships between classes, allowing us to model real-world scenarios by linking objects within a program. These relationships enable classes to work together without being hierarchically dependent on each other, unlike inheritance. Here, we&#8217;ll explain these relationships with examples and scenarios for a clear understanding. <a href=\"https:\/\/afzalbadshah.com\/index.php\/comprehensive-guide-to-object-oriented-programming-oop-in-java\/\" target=\"_blank\" rel=\"noopener\" title=\"\">You can visit the detailed tutorial here. <\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">1. <strong>Association in Java<\/strong><\/h3>\n\n\n\n<p>Association represents a simple <strong>&#8220;uses-a&#8221;<\/strong> relationship between two classes where objects of one class use objects of another class.<br>In this relationship, both classes are independent, and neither owns the other.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Example: Teacher and Student<\/strong><\/h3>\n\n\n\n<p>Imagine a scenario where a <code>Teacher<\/code> teacher teaches a <code>Student<\/code>.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A <code>Teacher<\/code> can teach many <code>Students<\/code>.<\/li>\n\n\n\n<li>A <code>Student<\/code> can be taught by many <code>Teachers<\/code>.<\/li>\n\n\n\n<li>Both <code>Teacher<\/code> and <code>Student<\/code> exist independently.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Code Example<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Student class representing a student\nclass Student {\n    private String name;\n\n    public Student(String name) {\n        this.name = name;\n    }\n\n    public String getName() {\n        return name;\n    }\n}\n\n\/\/ Teacher class that uses Student objects (Association)\nclass Teacher {\n    private String teacherName;\n\n    public Teacher(String teacherName) {\n        this.teacherName = teacherName;\n    }\n\n    public void teach(Student student) {\n        System.out.println(teacherName + \" is teaching \" + student.getName());\n    }\n}\n\n\/\/ Demonstration of Association\npublic class AssociationDemo {\n    public static void main(String&#91;] args) {\n        Student s1 = new Student(\"Ali\");\n        Student s2 = new Student(\"Sara\");\n\n        Teacher t1 = new Teacher(\"Dr. Afzal\");\n\n        \/\/ Teacher uses Student objects temporarily\n        t1.teach(s1);\n        t1.teach(s2);\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Explanation<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The <code>Teacher<\/code> class has a method <code>teach()<\/code> that uses a <code>Student<\/code> object as a parameter.<\/li>\n\n\n\n<li>The <code>Teacher<\/code> does <strong>not own<\/strong> the <code>Student<\/code>; they exist separately.<\/li>\n\n\n\n<li>If the <code>Teacher<\/code> object is destroyed, the <code>Student<\/code> objects remain unaffected.<\/li>\n<\/ul>\n\n\n\n<p>This relationship represents <strong>Association<\/strong> because it is a <strong>loose connection<\/strong> where objects interact but do not depend on each other\u2019s lifecycle.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2. Aggregation in Java<\/h3>\n\n\n\n<figure class=\"wp-block-image size-large\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"640\" height=\"360\" src=\"https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/11\/Composition-and-Aggregation-in-Java-2-1024x576.webp?resize=640%2C360&#038;ssl=1\" alt=\"\" class=\"wp-image-4765\" srcset=\"https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/11\/Composition-and-Aggregation-in-Java-2-jpg.webp?resize=1024%2C576&amp;ssl=1 1024w, https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/11\/Composition-and-Aggregation-in-Java-2-jpg.webp?resize=300%2C169&amp;ssl=1 300w, https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/11\/Composition-and-Aggregation-in-Java-2-jpg.webp?resize=768%2C432&amp;ssl=1 768w, https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/11\/Composition-and-Aggregation-in-Java-2-jpg.webp?resize=1536%2C864&amp;ssl=1 1536w, https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/11\/Composition-and-Aggregation-in-Java-2-jpg.webp?resize=480%2C270&amp;ssl=1 480w, https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/11\/Composition-and-Aggregation-in-Java-2-jpg.webp?w=1920&amp;ssl=1 1920w, https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/11\/Composition-and-Aggregation-in-Java-2-jpg.webp?w=1280&amp;ssl=1 1280w\" sizes=\"(max-width: 640px) 100vw, 640px\" \/><figcaption class=\"wp-element-caption\">Aggregation in Java<\/figcaption><\/figure>\n\n\n\n<p><strong>Aggregation<\/strong> represents a weaker relationship than composition. In aggregation, the contained (child) object can exist independently of the container (parent) object. In this case, the objects have their own lifecycles, and the destruction of one does not affect the existence of the other.                 <\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Example: <code>House<\/code> and <code>Person<\/code><\/h4>\n\n\n\n<p>Imagine a scenario where a <code>House<\/code> contains a list of <code>Person<\/code> objects as its residents. Even if the <code>House<\/code> object is destroyed, the <code>Person<\/code> objects (people) still exist. This relationship reflects aggregation, as <code>House<\/code> aggregates <code>Person<\/code> objects, but they are not exclusively dependent on each other.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Code Example:<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.ArrayList;\nimport java.util.List;\n\n\/\/ Person class representing individual residents\nclass Person {\n    private String name;\n\n    public Person(String name) {\n        this.name = name;\n    }\n\n    public String getName() {\n        return name;\n    }\n}\n\n\/\/ House class using Aggregation\nclass House {\n    private List&lt;Person&gt; residents;  \/\/ House \"has\" residents\n\n    public House() {\n        this.residents = new ArrayList&lt;&gt;();\n    }\n\n    public void addResident(Person person) {\n        residents.add(person);  \/\/ Aggregation: House contains references to Person objects\n    }\n\n    public void showResidents() {\n        System.out.println(\"House residents:\");\n        for (Person person : residents) {\n            System.out.println(person.getName());\n        }\n    }\n}\n\npublic class AggregationDemo {\n    public static void main(String&#91;] args) {\n        \/\/ Creating Person objects independently\n        Person person1 = new Person(\"Alice\");\n        Person person2 = new Person(\"Bob\");\n\n        \/\/ Creating House and adding residents\n        House house = new House();\n        house.addResident(person1);\n        house.addResident(person2);\n\n        house.showResidents();\n        \/\/ Output:\n        \/\/ House residents:\n        \/\/ Alice\n        \/\/ Bob\n    }\n}<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Explanation:<\/h4>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The <code>House<\/code> class has a list of <code>Person<\/code> objects, but these <code>Person<\/code> instances are created independently and are not owned by the <code>House<\/code>.<\/li>\n\n\n\n<li>If <code>House<\/code> is destroyed, the <code>Person<\/code> objects (people) still exist. This represents an aggregation relationship, where <code>House<\/code> and <code>Person<\/code> objects are loosely coupled and can exist independently.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">3. Composition in Java<\/h3>\n\n\n\n<figure class=\"wp-block-image size-large\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"640\" height=\"360\" src=\"https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/11\/Composition-and-Aggregation-in-Java-1-1024x576.webp?resize=640%2C360&#038;ssl=1\" alt=\"\" class=\"wp-image-4764\" srcset=\"https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/11\/Composition-and-Aggregation-in-Java-1-jpg.webp?resize=1024%2C576&amp;ssl=1 1024w, https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/11\/Composition-and-Aggregation-in-Java-1-jpg.webp?resize=300%2C169&amp;ssl=1 300w, https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/11\/Composition-and-Aggregation-in-Java-1-jpg.webp?resize=768%2C432&amp;ssl=1 768w, https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/11\/Composition-and-Aggregation-in-Java-1-jpg.webp?resize=1536%2C864&amp;ssl=1 1536w, https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/11\/Composition-and-Aggregation-in-Java-1-jpg.webp?resize=480%2C270&amp;ssl=1 480w, https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/11\/Composition-and-Aggregation-in-Java-1-jpg.webp?w=1920&amp;ssl=1 1920w, https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/11\/Composition-and-Aggregation-in-Java-1-jpg.webp?w=1280&amp;ssl=1 1280w\" sizes=\"(max-width: 640px) 100vw, 640px\" \/><figcaption class=\"wp-element-caption\">Composition in Java<\/figcaption><\/figure>\n\n\n\n<p><strong>Composition<\/strong> represents a strong relationship between two classes. If an object (child) is a part of another object (parent), and cannot exist independently, this relationship is known as composition. The lifecycle of the contained (child) object is bound to the lifecycle of the container (parent) object. In simpler terms, if the parent object is destroyed, the child object is also destroyed.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Example: <code>Car<\/code> and <code>Engine<\/code><\/h4>\n\n\n\n<p>Let&#8217;s consider a <code>Car<\/code> class that has an <code>Engine<\/code>. Here, a car cannot function without an engine, and if the car is destroyed, the engine is as well. This scenario makes <code>Engine<\/code> a part of <code>Car<\/code>, demonstrating a &#8220;part-of&#8221; relationship.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Code Example:<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Engine class representing the part of a Car\nclass Engine {\n    private String type;\n\n    public Engine(String type) {\n        this.type = type;\n    }\n\n    public String getType() {\n        return type;\n    }\n\n    public void start() {\n        System.out.println(\"Engine of type \" + type + \" is starting.\");\n    }\n}\n\n\/\/ Car class that uses Composition\nclass Car {\n    private Engine engine;  \/\/ Car \"has-an\" Engine\n\n    public Car(String engineType) {\n        this.engine = new Engine(engineType);  \/\/ Composition: Engine is created and owned by Car\n    }\n\n    public void startCar() {\n        System.out.println(\"Car is starting.\");\n        engine.start();  \/\/ Car depends on Engine's functionality\n    }\n\n    public void showDetails() {\n        System.out.println(\"Car with engine type: \" + engine.getType());\n    }\n}\n\npublic class CompositionDemo {\n    public static void main(String&#91;] args) {\n        Car car = new Car(\"V8\");\n        car.startCar();\n        car.showDetails();\n        \/\/ Output:\n        \/\/ Car is starting.\n        \/\/ Engine of type V8 is starting.\n        \/\/ Car with engine type: V8\n    }\n}<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Explanation:<\/h4>\n\n\n\n<ul class=\"wp-block-list\">\n<li>In this example, <code>Car<\/code> contains an <code>Engine<\/code> object. The <code>Engine<\/code> is a part of <code>Car<\/code>, and it is created inside the <code>Car<\/code> constructor. This means that without <code>Car<\/code>, there is no independent <code>Engine<\/code>.<\/li>\n\n\n\n<li>This relationship is composition because the <code>Engine<\/code> is entirely dependent on the existence of <code>Car<\/code>.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Comparison of Composition and Aggregation<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th><strong>Aspect<\/strong><\/th><th><strong>Association<\/strong><\/th><th><strong>Aggregation<\/strong><\/th><th><strong>Composition<\/strong><\/th><\/tr><\/thead><tbody><tr><td><strong>Relationship<\/strong><\/td><td>Uses-a<\/td><td>Has-a<\/td><td>Part-of<\/td><\/tr><tr><td><strong>Dependency<\/strong><\/td><td>No dependency between objects<\/td><td>Weak dependency<\/td><td>Strong dependency<\/td><\/tr><tr><td><strong>Object Lifecycle<\/strong><\/td><td>Independent: both objects live separately<\/td><td>Independent: child can exist without parent<\/td><td>Dependent: child cannot exist without parent<\/td><\/tr><tr><td><strong>Example<\/strong><\/td><td>Teacher and Student<\/td><td>House and Person<\/td><td>Car and Engine<\/td><\/tr><tr><td><strong>Implementation<\/strong><\/td><td>One class uses another through a reference or method parameter<\/td><td>Parent holds references to existing objects created outside<\/td><td>Contained object is created and owned inside the parent class<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Composition and aggregation are essential in creating flexible and reusable class structures in object-oriented programming, allowing for modular designs that can represent complex relationships.<\/p>\n\n\n\n<p><a href=\"https:\/\/www.canva.com\/design\/DAGWRwFvcxA\/4uRwuSYXZUIl0FA-4l7sNQ\/view?utm_content=DAGWRwFvcxA&amp;utm_campaign=designshare&amp;utm_medium=link&amp;utm_source=editor\" target=\"_blank\" rel=\"noopener\" title=\"\">Visit the detailed presentation here. <\/a><\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In Java, Association, composition, and aggregation define relationships between classes, allowing us to model real-world scenarios by linking objects within a program. These relationships enable classes to work together without being hierarchically dependent on each other, unlike inheritance. Here, we&#8217;ll explain these relationships with examples and scenarios for a clear understanding. You can visit the detailed tutorial here. 1. Association in Java Association represents a simple &#8220;uses-a&#8221; relationship between two classes where objects of one class use objects of another&#8230;<\/p>\n<p class=\"read-more\"><a class=\"btn btn-default\" href=\"https:\/\/afzalbadshah.com\/index.php\/2024\/11\/12\/composition-and-aggregation-in-java\/\"> Read More<span class=\"screen-reader-text\">  Read More<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":4763,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"enabled":false},"version":2}},"categories":[602],"tags":[563,636,603],"class_list":["post-4760","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-object-oriented-programing-oop","tag-aggregation","tag-composition","tag-oop"],"aioseo_notices":[],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/11\/Composition-and-Aggregation-in-Java-jpg.webp?fit=1920%2C1080&ssl=1","jetpack_sharing_enabled":true,"jetpack_likes_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/pf3emP-1eM","jetpack-related-posts":[],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/4760","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/comments?post=4760"}],"version-history":[{"count":8,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/4760\/revisions"}],"predecessor-version":[{"id":6580,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/4760\/revisions\/6580"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/media\/4763"}],"wp:attachment":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/media?parent=4760"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/categories?post=4760"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/tags?post=4760"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}