• Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Difference between dependency and composition?

Definitions taken from here

Change in structure or behaviour of a class affects the other related class, then there is a dependency between those two classes. It need not be the same vice-versa. When one class contains the other class it this happens.

Composition

Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition.

Concrete examples in Java from here and here

  • dependencies
  • composition

Community's user avatar

  • The quality of those definitions is quite poor. Example: "...dependency between those two classes" "It need not be the same vice-versa" But "between" is an undirected relationship---it is the same vice-versa by definition of the term between . –  Marko Topolnik Jan 9, 2014 at 13:50
  • 1 Can you give me an example in code please :) –  danihodovic Jan 9, 2014 at 13:51
  • @MarkoTopolnik An example of dependecy and composition where I can clearly understand the differance. In code if possible –  danihodovic Jan 9, 2014 at 13:53

4 Answers 4

The difference can be seen in the two constructors:

Dependency : The Address object comes from outside , it's allocated somewhere else. This means that the Address and Employee objects exists separately, and only depend on each other.

Composition : Here you see that a new Engine is created inside Car . The Engine object is part of the Car . This means that a Car is composed of an Engine .

meaning-matters's user avatar

  • 3 So dependency == aggregation? stackoverflow.com/questions/11881552/… –  danihodovic Jan 9, 2014 at 15:04
  • 1 @dani-h No, aggregation and composition describe how things are build/structured, while dependency is more a property of a certain structure. See @TheLostMind's great answer. –  meaning-matters Jan 9, 2014 at 16:12

Simply put :

Thanks to Marko Topolnik for this...

Dependency occurs when one object "is dependent" on another. It can occur with or without a relation between the 2 objects. Actually, one object might not even be knowing that another exists, yet they might be dependent. Example : The Producer-Consumer problem. The producer need not know that the consumer exists, yet it has to do wait() and notify(). So, "NO" , dependency is not a subset of association.

Composition : Is a type of association in which the "child" object cannot exist without the parent class. i.e, if the child object exists, then it MUST BE IN THE parent Object and nowhere else.

EG: A Car(Parent) has Fuel injection system(child). Now, it makes no sense to have a Fuel Injection system outside a car (it will be of no use). i.e, Fuel injection system cannot exist without the car.

Aggregation : Here, the child object can exist outside the parent object. A Car has a Driver. The Driver CAN Exist outside the car.

TheLostMind's user avatar

  • So you are saying a composition is a subset of a dependency? –  danihodovic Jan 9, 2014 at 13:56
  • 1 Yes... Dependency is a general term.. Composition/aggregation/inheritance lead to dependency. Though I think association is a better term to use instead of dependency. –  TheLostMind Jan 9, 2014 at 13:57
  • Can you show me the source of this? Because the two answers I've got contradict each other. Also, they appear differently in UML, which one should be used in class diagrams for instance? –  danihodovic Jan 9, 2014 at 13:58
  • If the definition of dependency is "a change in structure/behavior influences a class", then there has to be no aggregation or any other type of relationship between the classes. They may both, for example, access the same third object , and must agree on the ways they are using that object. Typical example: the Producer/Consumer pattern. –  Marko Topolnik Jan 9, 2014 at 14:00
  • 3 Quoting myself from the above comment: Typical example: the Producer/Consumer pattern . Both producer and consumer aggregate a Queue object, but otherwise are completely decoupled and don't know about each other. However, changing the behaviour of the Producer will influence (and possibly break) the behaviour of the Consumer. –  Marko Topolnik Jan 9, 2014 at 14:22

Dependency refers to usage of objects only within a functions scope. In other words, instances of the class only exist within the functions (or methods) of the containing class, and are destroyed after functions exit.

The example you gave for Dependency is not a Dependency because the Employee class contains an instance of an Address, this is called an Aggregation. An aggregation is like a Composition except the object can also exist outside of the class which is using it. (It can be located outside the classes scope). In your example you are passing a copy of an Address to the Employee constructor. But since it is created outside of the Employee object, the Address may also exist else where in the program.

Just as with Aggregation, Composition is where the component object is available to the entire composite object. This means that all the methods/functions of the composite object can access the component object. The only difference between Aggregation and Composition is that in Composition the component object only exists inside the composite object and no where else in the program. So when the composite object is destroyed, the given component object is also destroyed, and can not exist anywhere else. In your example, The Car is a composite object and the Engine is a component because that instance of the Engine only exists in that particular Car and no where else.

kiwicomb123's user avatar

Composition will necessarily, always utilize dependency injection.

However, it is possible to do dependency injection without it constituting composition.

Practically speaking, if you get to concrete code, whether composition occurs or not is determined by whether your save the argument passed via dependency injection as a member variable in the instantiated object when instantiating or not. If you do, it's composition. If you don't, it's not.

Definitions

Dependency injection in simplified terms is adding a parameter to an capsulating chunk block of code (e.g. class, function, block, etc.), as opposed to using the literal procedural code that would be used without the parameter.

Composition is when you use a dependency injected parameter/argument upon instantiating the object being composed

Dependency injection with composition

The Syringe class is composed of Drug, since Syringe saves drug as a member variable.

Aside: Syringe could conceivably be composed of multiple dependencies, not just the single drug dependency (pun alert!), but even this degenerate case of a single-dependency composition constitutes composition nonetheless. If it helps, imagine if you had to compose a Syringe object from a Drug object as well as a Needle object, the needle object having a specific value among many possible gauges and lengths as well.

Dependency injection without composition

This next example is not composition because it does not save 'drug' when instantiating 'syringe'.

Instead, 'drug' is used directly in a member function.

ahnbizcad's user avatar

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct .

Not the answer you're looking for? Browse other questions tagged java oop dependencies uml composition or ask your own question .

  • The Overflow Blog
  • Journey to the cloud part II: Migrating Stack Overflow for Teams to Azure
  • Featured on Meta
  • Our Design Vision for Stack Overflow and the Stack Exchange network
  • Sunsetting Winter/Summer Bash: Rationale and Next Steps
  • Discussions experiment launching on NLP Collective
  • Temporary policy: Generative AI (e.g., ChatGPT) is banned
  • Testing an AI-generated content policy banner on Stack Overflow

Hot Network Questions

  • How to divide a circle into three equal circles using PGF/TikZ?
  • Is Latin qui a descendant or predecessor of Persian که (kë)?
  • Lower limit under \mathbb
  • Are journals supposed to avoid publishing papers from persons of notorious reputation?
  • How to leave only specific columns?
  • What does „fecerunt pedes“ mean in Latin inscriptions?
  • How do I know this is a right triangle?
  • Bovine colostrum for infant puppy
  • Are non-Jews rewarded for following the Torah?
  • Is it normal for an LED bulb to become hot to the touch?
  • How to interpret External Clearance spec on HCPL3700M IC?
  • Why can't lunar rovers survive long duration nights?
  • Is "may exist" and "may not exist" a negation that isn't a contradiction?
  • For magical tinkering, do you need to touch the object with your tool?
  • Analogous results in geometric group theory and Riemannian geometry?
  • PVC water pipe used for electical wires to workshop
  • Spanish equivalent of "making jokes/having fun at someone's expense"?
  • Sums in a (very small) box
  • Why and how to write clear code comments and when will documentations be needed beyond code commenting?
  • What can I call actions that seem to motivate employees to give gifts to a senior?
  • How to make USB flash drive immutable/read only forever?
  • How does pre-payment affect an adjustable-rate mortgage?
  • Why did Japanese borrow words for simple numbers from Chinese?
  • How do you know mercury changes monotonically with temperature if mercury itself is used to make the thermometer?

what is composition java

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot
  • Write an Interview Experience
  • Share Your Campus Experience
  • Java Tutorial

Overview of Java

  • Introduction to Java
  • The complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works – JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?

Basics of Java

  • Java Basic Syntax
  • Java Hello World Program
  • Java Data Types
  • Primitive data type vs. Object data type in Java with Examples
  • Java Identifiers

Operators in Java

  • Java Variables
  • Scope of Variables In Java

Wrapper Classes in Java

Input/output in java.

  • How to Take Input From User in Java?
  • Scanner Class in Java
  • Java.io.BufferedReader Class in Java
  • Difference Between Scanner and BufferedReader Class in Java
  • Ways to read input from console in Java
  • System.out.println in Java
  • Difference between print() and println() in Java
  • Formatted output in Java
  • Fast I/O in Java in Competitive Programming

Flow Control in Java

  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Java Arithmetic Operators with Examples
  • Java Unary Operator with Examples
  • Java Assignment Operators with Examples
  • Java Relational Operators with Examples
  • Java Logical Operators with Examples
  • Java Ternary Operator with Examples
  • Bitwise Operators in Java
  • Strings in Java
  • String class in Java
  • Java.lang.String class in Java | Set 2
  • Why Java Strings are Immutable?
  • StringBuffer class in Java
  • StringBuilder Class in Java with Examples
  • String vs StringBuilder vs StringBuffer in Java
  • StringTokenizer Class in Java
  • StringTokenizer Methods in Java with Examples | Set 2
  • StringJoiner Class in Java
  • Arrays in Java
  • Arrays class in Java
  • Multidimensional Arrays in Java
  • Different Ways To Declare And Initialize 2-D Array in Java
  • Jagged Array in Java
  • Final Arrays in Java
  • Reflection Array Class in Java
  • util.Arrays vs reflect.Array in Java with Examples

OOPS in Java

  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods

Access Modifiers in Java

  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java

Inheritance in Java

Abstraction in java, encapsulation in java, polymorphism in java, interfaces in java.

  • ‘this’ reference in Java
  • Inheritance and Constructors in Java
  • Java and Multiple Inheritance
  • Interfaces and Inheritance in Java

Association, Composition and Aggregation in Java

  • Comparison of Inheritance in C++ and Java
  • abstract keyword in java
  • Abstract Class in Java
  • Difference between Abstract Class and Interface in Java
  • Control Abstraction in Java with Examples
  • Difference Between Data Hiding and Abstraction in Java
  • Difference between Abstraction and Encapsulation in Java with Examples
  • Difference between Inheritance and Polymorphism
  • Dynamic Method Dispatch or Runtime Polymorphism in Java
  • Difference between Compile-time and Run-time Polymorphism in Java

Constructors in Java

  • Copy Constructor in Java
  • Constructor Overloading in Java
  • Constructor Chaining In Java with Examples
  • Private Constructors and Singleton Classes in Java

Methods in Java

  • Static methods vs Instance methods in Java
  • Abstract Method in Java with Examples
  • Overriding in Java
  • Method Overloading in Java
  • Difference Between Method Overloading and Method Overriding in Java
  • Differences between Interface and Class in Java
  • Functional Interfaces in Java
  • Nested Interface in Java
  • Marker interface in Java
  • Comparator Interface in Java with Examples
  • Need of Wrapper Classes in Java
  • Different Ways to Create the Instances of Wrapper Classes in Java
  • Character Class in Java
  • Java.Lang.Byte class in Java
  • Java.Lang.Short class in Java
  • Java.lang.Integer class in Java
  • Java.Lang.Long class in Java
  • Java.Lang.Float class in Java
  • Java.Lang.Double Class in Java
  • Java.lang.Boolean Class in Java
  • Autoboxing and Unboxing in Java
  • Type conversion in Java with Examples

Keywords in Java

  • List of all Java Keywords
  • Important Keywords in Java
  • Super Keyword in Java
  • final Keyword in Java
  • static Keyword in Java
  • enum in Java
  • transient keyword in Java
  • volatile Keyword in Java
  • final, finally and finalize in Java
  • Public vs Protected vs Package vs Private Access Modifier in Java
  • Access and Non Access Modifiers in Java

Memory Allocation in Java

  • Java Memory Management
  • How are Java objects stored in memory?
  • Stack vs Heap Memory Allocation
  • How many types of memory areas are allocated by JVM?
  • Garbage Collection in Java
  • Types of JVM Garbage Collectors in Java with implementation details
  • Memory leaks in Java
  • Java Virtual Machine (JVM) Stack Area

Classes of Java

  • Understanding Classes and Objects in Java
  • Java Singleton Class
  • Object Class in Java
  • Inner Class in Java
  • Throwable Class in Java with Examples

Packages in Java

  • Packages In Java
  • How to Create a Package in Java?
  • Java.util Package in Java
  • Java.lang package in Java
  • Java.io Package in Java
  • Java Collection Tutorial

Exception Handling in Java

  • Exceptions in Java
  • Types of Exception in Java with Examples
  • Checked vs Unchecked Exceptions in Java
  • Try, catch, throw and throws in Java
  • Flow control in try catch finally in Java
  • throw and throws in Java
  • User-defined Custom Exception in Java
  • Chained Exceptions in Java
  • Null Pointer Exception In Java
  • Exception Handling with Method Overriding in Java
  • Multithreading in Java
  • Lifecycle and States of a Thread in Java
  • Java Thread Priority in Multithreading
  • Main thread in Java
  • Java.lang.Thread Class in Java
  • Runnable interface in Java
  • Naming a thread and fetching name of current thread in Java
  • What does start() function do in multithreading in Java?
  • Difference between Thread.start() and Thread.run() in Java
  • Thread.sleep() Method in Java With Examples
  • Synchronization in Java
  • Importance of Thread Synchronization in Java
  • Method and Block Synchronization in Java
  • Lock framework vs Thread synchronization in Java
  • Difference Between Atomic, Volatile and Synchronized in Java
  • Deadlock in Java Multithreading
  • Deadlock Prevention And Avoidance
  • Difference Between Lock and Monitor in Java Concurrency
  • Reentrant Lock in Java

File Handling in Java

  • Java.io.File Class in Java
  • Java Program to Create a New File
  • Different ways of Reading a text file in Java
  • Java Program to Write into a File
  • Delete a File Using Java
  • File Permissions in Java
  • FileWriter Class in Java
  • Java.io.FileDescriptor in Java
  • Java.io.RandomAccessFile Class Method | Set 1
  • Regular Expressions in Java
  • How to write Regular Expressions?
  • Matcher pattern() method in Java with Examples
  • Pattern pattern() method in Java with Examples
  • Quantifiers in Java
  • java.lang.Character class methods | Set 1
  • Java IO : Input-output in Java with Examples
  • Java.io.Reader class in Java
  • Java.io.Writer Class in Java
  • Java.io.FileInputStream Class in Java
  • FileOutputStream in Java
  • Java.io.BufferedOutputStream class in Java
  • Java Networking
  • TCP/IP Model
  • User Datagram Protocol (UDP)
  • Differences between IPv4 and IPv6
  • Difference between Connection-oriented and Connection-less Services
  • Socket Programming in Java
  • java.net.ServerSocket Class in Java
  • URL Class in Java with Examples
  • Discuss(40+)

Association is a relation between two separate classes which establishes through their Objects. Association can be one-to-one, one-to-many, many-to-one, many-to-many. In Object-Oriented programming, an Object communicates to another object to use functionality and services provided by that object. Composition and Aggregation are the two forms of association. 

Output Explanation: In the above example, two separate classes Bank and Employee are associated through their Objects. Bank can have many employees, So it is a one-to-many relationship. 

Aggregation

It is a special form of Association where:  

  • It represents Has-A’s relationship.
  • It is a unidirectional association i.e. a one-way relationship. For example, a department can have students but vice versa is not possible and thus unidirectional in nature.
  • In Aggregation, both entries can survive individually which means ending one entity will not affect the other entity.

Output Explanation: In this example, there is an Institute which has no. of departments like CSE, EE. Every department has no. of students. So, we make an Institute class that has a reference to Object or no. of Objects (i.e. List of Objects) of the Department class. That means Institute class is associated with Department class through its Object(s). And Department class has also a reference to Object or Objects (i.e. List of Objects) of the Student class means it is associated with the Student class through its Object(s). 

It represents a Has-A relationship. In the above example: Student Has-A name. Student Has-A ID. Student Has-A Dept. Department Has-A Students as depicted from the below media.   

When do we use Aggregation ??   Code reuse is best achieved by aggregation.  

Concept 3: Composition  

Composition

Composition is a restricted form of Aggregation in which two entities are highly dependent on each other.  

  • It represents part-of relationship.
  • In composition, both entities are dependent on each other.
  • When there is a composition between two entities, the composed object cannot exist without the other entity.

Example Library

Output explanation: In the above example, a library can have no. of books on the same or different subjects. So, If Library gets destroyed then All books within that particular library will be destroyed. i.e. books can not exist without libraries. That’s why it is composition.  Book is Part-of Library.

Aggregation vs Composition 

1. Dependency: Aggregation implies a relationship where the child can exist independently of the parent. For example, Bank and Employee, delete the Bank and the Employee still exist. whereas Composition implies a relationship where the child cannot exist independent of the parent. Example: Human and heart, heart don’t exist separate to a Human

2. Type of Relationship: Aggregation relation is “has-a” and composition is “part-of” relation.

3. Type of association: Composition is a strong Association whereas Aggregation is a weak Association.

In case of aggregation, the Car also performs its functions through an Engine. but the Engine is not always an internal part of the Car. An engine can be swapped out or even can be removed from the car. That’s why we make The Engine type field non-final.

This article is contributed by Nitsdheerendra . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Please Login to comment...

  • bipin_kumar
  • tushargupta09
  • arorakashish0911
  • simranarora5sos
  • simmytarika5
  • surindertarika1234
  • sumitgumber28
  • varshagumber28
  • sagar0719kumar
  • singghakshay
  • kashishsoda
  • chaitanyadeshmukh321
  • girishjn618
  • java-inheritance
  • Java-Object Oriented

what is composition java

Improve your Coding Skills with Practice

  • United States
  • United Kingdom

Rafael del Nero

By Rafael del Nero , Java Developer, JavaWorld |

Tease your mind and test your learning, with these quick introductions to challenging concepts in Java programming.

Java inheritance vs. composition: How to choose

Compare inheritance and composition, the two fundamental ways to relate java classes, then practice debugging classcastexceptions in java inheritance..

abstract connections / network / object / root / inheritance / hierarchy

When to use inheritance in Java

When to use composition in java, inheritance vs composition: two examples, method overriding with java inheritance, using constructors with inheritance, type casting and the classcastexception, take the java inheritance challenge.

  • What just happened?
  • Learn more about Java

Inheritance and composition are two programming techniques developers use to establish relationships between classes and objects. Whereas inheritance derives one class from another, composition defines a class as the sum of its parts.

Classes and objects created through inheritance are tightly coupled because changing the parent or superclass in an inheritance relationship risks breaking your code. Classes and objects created through composition are loosely coupled , meaning that you can more easily change the component parts without breaking your code.

Because loosely coupled code offers more flexibility, many developers have learned that composition is a better technique than inheritance, but the truth is more complex. Choosing a programming tool is similar to choosing the correct kitchen tool: You wouldn't use a butter knife to cut vegetables, and in the same way you shouldn't choose composition for every programming scenario. 

In this Java Challenger you'll learn the difference between inheritance and composition and how to decide which is correct for your program . Next, I'll introduce you to several important but challenging aspects of Java inheritance: method overriding, the super keyword, and type casting. Finally, you'll test what you've learned by working through an inheritance example line by line to determine what the output should be.

In object-oriented programming, we can use inheritance when we know there is an "is a" relationship between a child and its parent class. Some examples would be:

  • A person is a human.
  • A cat is an animal.
  • A car is a   vehicle.

In each case, the child or subclass is a specialized version of the parent or superclass. Inheriting from the superclass is an example of code reuse. To better understand this relationship, take a moment to study the Car class, which inherits from Vehicle :

When you are considering using inheritance, ask yourself whether the subclass really is a more specialized version of the superclass. In this case, a car is a type of vehicle, so the inheritance relationship makes sense. 

In object-oriented programming, we can use composition in cases where one object "has" (or is part of) another object. Some examples would be:

  • A car has a battery (a battery is part of a car).
  • A person has a heart  (a heart is part of a person).
  • A house has a living room (a living room is part of a house).

To better understand this type of relationship, consider the composition of a House :

In this case, we know that a house has a living room and a bedroom, so we can use the Bedroom and  LivingRoom objects in the composition of a House . 

Consider the following code. Is this a good example of inheritance?

In this case, the answer is no. The child class inherits many methods that it will never use, resulting in tightly coupled code that is both confusing and difficult to maintain. If you look closely, it is also clear that this code does not pass the "is a" test.

Now let's try the same example using composition:

Using composition for this scenario allows the  CharacterCompositionExample class to use just two of HashSet 's methods, without inheriting all of them. This results in simpler, less coupled code that will be easier to understand and maintain.

Inheritance allows us to reuse the methods and other attributes of one class in a new class, which is very convenient.  But for inheritance to really work, we also need to be able to change some of the inherited behavior within our new subclass.  For instance, we might want to specialize the sound a Cat makes:

This is an example of Java inheritance with method overriding. First, we extend the Animal class to create a new Cat class. Next, we override the Animal class's emitSound() method to get the specific sound the Cat makes. Even though we've declared the class type as Animal , when we instantiate it as Cat we will get the cat's meow. 

Does Java have multiple inheritance?

Unlike some languages, such as C++, Java does not allow multiple inheritance with classes. You can use multiple inheritance with interfaces, however. The difference between a class and an interface, in this case, is that interfaces don't keep state.

If you attempt multiple inheritance like I have below, the code won't compile:

A solution using classes would be to inherit one-by-one:

Another solution is to replace the classes with interfaces:

Using ‘super' to access parent classes methods

When two classes are related through inheritance, the child class must be able to access every accessible field, method, or constructor of its parent class. In Java, we use the reserved word super to ensure the child class can still access its parent's overridden method:

In this example, Character is the parent class for Moe.  Using super , we are able to access Character 's  move() method in order to give Moe a beer.

When one class inherits from another, the superclass's constructor always will be loaded first, before loading its subclass. In most cases, the reserved word super will be added automatically to the constructor.  However, if the superclass has a parameter in its constructor, we will have to deliberately invoke the super constructor, as shown below:

If the parent class has a constructor with at least one parameter, then we must declare the constructor in the subclass and use super to explicitly invoke the parent constructor. The super reserved word won't be added automatically and the code won't compile without it.  For example:

Casting is a way of explicitly communicating to the compiler that you really do intend to convert a given type.  It's like saying, "Hey, JVM, I know what I'm doing so please cast this class with this type." If a class you've cast isn't compatible with the class type you declared, you will get a ClassCastException .

In inheritance, we can assign the child class to the parent class without casting but we can't assign a parent class to the child class without using casting.

Consider the following example:

When we try to cast an Animal instance to a Dog we get an exception. This is because the Animal doesn't know anything about its child. It could be a cat, a bird, a lizard, etc. There is no information about the specific animal. 

The problem in this case is that we've instantiated Animal like this:

Then tried to cast it like this:

Because we don't have a Dog instance, it's impossible to assign an Animal to the Dog .  If we try, we will get a ClassCastException . 

In order to avoid the exception, we should instantiate the Dog like this:

then assign it to Animal :

In this case, because  we've extended the Animal class, the Dog instance doesn't even need to be cast; the Animal parent class type simply accepts the assignment.

Casting with supertypes

It's possible to declare a Dog with the supertype Animal , but if we want to invoke a specific method from Dog , we will need to cast it. As an example, what if we wanted to invoke the bark() method?  The Animal supertype has no way to know exactly what animal instance we're invoking, so we have to cast Dog manually before we can invoke the bark() method:

You can also use casting without assigning the object to a class type. This approach is handy when you don't want to declare another variable:

You've learned some important concepts of inheritance, so now it's time to try out an inheritance challenge. To start, study the following code:

  • Programming Languages
  • Software Development

what is composition java

Getting Started with Composition in Java

November 24, 2021.

Like most OOP languages, Java does not allow multiple inheritances. This problem limits the programmer from applying code re-use with more objects with strong relationships or similar properties.

To solve this problem, there is a property called Composition . Composition in Java exists when two or more objects relate to each other. One object, in that case, exists due to the existence of another.

Composition in Java

It also occurs when a class references one or more objects of other classes in a single instance. For example, a Class Car is a composition of class Engine and class wheels and a Class Body is a composition of the class Heart, class Stomach, etc.

The examples above show that neither the class Engine nor the class Wheels can exist without the class Car. Likewise, the class Heart and Class stomach both depend on the class Body to exist.

There are two categories of classes. First, the Parent class is usually independent. For instance, the Class Car and the Class Body are parent classes.

However, there is the dependent class that cannot exist without the presence of the parent class. This class is known as the child class . For example, Class Engine , Class Wheels from the parent Class Car , Class Heart , and the Class Stomach are child classes of the parent class Body .

Features of Composition

Below are some of the common features available when interacting with composition.

It provides a has-a relationship between objects: Let us use the example of the car and the Engine to understand this. Both the car and the Engine are objects, but the Engine is contained in the car, meaning every car has an engine. In composition, one object must have the other hence the has-a relationship.

Code Re-use: This feature ensures code re-use. From the above example, the class engine, once written can be re-used on another object car. Since it will still contain the Engine and will require the engine class. This saves the programmer having to code the engine class for every car even though the attributes of the cars may be different.

Implementation on Java

Now, we are going to learn how composition is applied in problem-solving. We will be using the Intellij IDE with the Java language. If you do not have Intellij , you can download it from the Jetbrains official Webpage.

We will create three classes: the Main Class, the Parent class, and the child class. We will be running the programs at the Main class and creating the methods and attributes at the parent and child classes. Therefore, ensure that all your classes are in the same package for a swift code execution.

We have created a class named Engine from the above code. We have allocated some attributes and given all the access specifiers private to make it only accessible by the class itself or via the getters from another class. We also have getters and setters to enable the attributes accessible from an outside class.

We will now create the parent class, which is the class Vehicle. Finally, we will link the Class Engine with the Class Vehicle by creating an Engine attribute.

We have treated the child class Engine as an attribute, even though it is not. So we have initialized it, created a constructor for it, and created a getter and setter for it, just like any other attribute. Let us now create the Main class where we will run and implement the code.

The Main class, java, enables you to run all the code in the package specified. You first create an object, the vehicle; for our case, we have a Benz . We also created an Engine.

A preview of the full code as in the Intellij is as shown below:

Main Page

The output of the code is derived through composition.

Difference between Composition and Inheritance

Inheritance is a property where an object acquires all the attributes and behaviour with similar properties, commonly known as parent object .

Composition differs from inheritance in the following ways:

  • Composition is based on a has-a relationship, while inheritance is based on an is-a relationship.
  • With inheritance, you can extend your code to only one interface, but with composition, you can re-use your code multiple times.
  • With composition, we can re-use code even with the final class, but it cannot be achieved with inheritance.

Let us now use a code snippet to show how composition is evaluated.

This article went through how composition can be pretty helpful while coding. By utilizing code re-use, one can have a cleaner and more organized code with maximum characters.

Composition helps locate bugs in your code since the neat arrangement enables straightforward code interpretation. Below are a few other critical concepts that we went over in the tutorial:

  • Introduction to composition in Java.
  • Features available in composition.
  • Implementation of Composition using an example.
  • Difference between Composition and Inheritance.

Happy coding!

Peer Review Contributions by: Jerim Kaura

Similar Articles

Create a Basic Browser GraphiQL Tool using React.js, Node.js and MongoDB

How to Create a Basic Browser GraphiQL Tool using React.js, Node.js and MongoDB

Stir Framework hero image

Stir Framework in Action in a Spring Web App

How to Create a Reusable React Form component Hero Image

How to Create a Reusable React Form component

What is Composition in Java? With Examples

What is Composition in Java? With Examples

Basics of Association in Java:

Association can be defined in Java as an interconnection between two individual classes using their distinct objects. The types of relationships managed by Java association are:

  • One-to-one: There exists only a single derived class for each parent class.
  • One-to-many: A single parent class may have more than one child class. 
  • Many-to-one: A single child class may be associated with more than one superclass.
  • Many-to-many: A number of parent classes may be associated with a single child class and more number of child classes may be associated with a single parent class. 

Once the relationship is established, the derived classes communicate with the respective base classes to reuse their characteristics and properties. There are two types of association in Java. They are aggregation and composition.

Aggregation in Java is a more generalized process as compared to the composition. These forms are based on the type of relationship supported between the classes. 

Introduction to Composition in Java:

A designing technique in Java that implements a Has-A relationship is referred to as composition. The process of inheritance is used to reuse the code. The composition in Java can be accomplished using an instance variable referring to other objects. If an object constitutes another object in such a way that the constituent object cannot exist without the survival of the main object, the kind of relationship is referred to as the composition. To be more specific, the composition is an aspect that describes the reference among two or more classes with the help of instance variables. Here, the instance should be created before using the instant variables. Let us take an example of a Library for a clear understanding of the concept ‘composition’.

Ads of upGrad blog

There exist numerous books in a library. Each book has separate authors and titles. The library should also have a reference list of books in it. The library also has several books related to the same subject or diverse subjects. Here, the library corresponds to the main class and the books can be related to the derived class. The association or the relationship between the books and the library can be regarded as composition. This is because the class “Books” is completely dependent on the class library. For instance, if the library is destroyed, then all the books in it are also destroyed. 

Check out our  free technology courses  to get an edge over the competition.

Explore our Popular Software Engineering Courses

A detailed description of composition in java:.

The Composition is a form of Java association. The two communicating classes are strongly interlinked, where the derived class is completely dependent on the parent class. The independent existence of the derived class is not possible in this case. For example, an engine without a car cannot exist independently. This association type is highly restricted as compared to the aggregation. Composition is a design technique and should not be confused with a Java feature. 

The Composition can be used to model objects that have other objects as their constituent members. There exists the has-a relationship between these objects. In this association type, one object contains the other object. Hence, the constituent object is completely dependent on the main object for its survival. So, if the containing object is ruined, the constituent object is also affected. Therefore, the composition relationship can be viewed as a part of the whole relationship in which the existence of the part without the whole is not possible. In other words, the part is automatically deleted on the deletion of the whole. This implies that the whole has a firm relationship with the part. 

Learn  Software Development Courses  online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.

In-Demand Software Development Skills

Why prefer composition over inheritance .

  • Classes should use composition instead of inheritance from a parent class to enable polymorphic behavior and code reuse. According to the design concept, the composition should be preferred over inheritance to get a better level of design flexibility. 
  • One justification for choosing composition in Java is the lack of support for multiple inheritances. Since Java only allows for the extension of a single class, Reader and Writer functionality is required if you require multiple features, such as the ability to read and write character data into files. Having them as private members simplifies your task, and this is what is meant by composition.
  • Flexibility is another factor that makes composition superior to inheritance. If you use composition, you have the flexibility to swap out an outdated and improved Composed class implementation. Utilizing the comparator class, which offers features for comparison, is one example.
  • The ability to reuse code is provided by both composition and inheritance. However, inheritance has the drawback of breaking encapsulation. If the subclass’s function depends on the superclass’s action, it suddenly becomes fragile. Sub-class functionality may become unusable when the behavior of the super-class changes without any change on the part of the sub-class.
  • Multiple object-oriented design patterns from Gang of Four: Elements of Reusable Object-Oriented Software, listed in the timeless classic Design Patterns, favor composition over inheritance. The strategy design pattern serves as the finest example of this, using composition and delegation to alter the Context’s behavior without altering the context code. Because Context relies on composition to carry strategy instead of inheriting it, it is easy to have a new implementation of strategy at run-time.

Composition In Java Example

The types of association used to depict the link between two classes are aggregation and composition in java . In the case of composition, If an existing university object is destroyed, all of the department objects will also be destroyed automatically because there is no way for dependent objects to exist without an existing university object. This strong association between the objects is what is meant by the term composition.

How Does Composition Work in Java?

Since the PART-OF type of relation between two entities is implemented using composition, one of the entities is referred to as a container and the other as a composed entity.  The ability to utilize this class as a composite entity in other container classes encourages code reuse. A composition in Java example can include a container class for an engine being a car, a two-wheeler, etc.

Both have dependencies on one another since the combined class is a component of a container entity. However, a composed class can still be void; for example, a car need not be required to have an engine. As a result, the container class serves as the sole source of existence for the composed class. PART-OF relation is also referred to as a subclass of HAS-A relation because Composition is a type of association. Composition assists in establishing a relationship between two entities that are interdependent without the use of inheritance in this way.

How is inheritance different from composition in Java?

It is important to note that the functionality of inheritance can be accomplished using composition in Java as well. Though both inheritance and composition are used to offer reusability of the code by the relating class, there are subtle differences between these two. The main difference between the two processes is that composition is a technique of design, unlike inheritance which is a Java feature. Other major differences between the two are listed in the table below.

Differences between Aggregation and Composition:

Read our popular articles related to software development, advantages of using composition in java:.

  • Composition facilitates the reuse of the Java code.
  • Though multiple inheritances are not supported by Java, the gap can be filled in by this design technique.
  • With the use of composition, a class can be tested for ability in a better manner.
  • The code is made more flexible with the use of composition. The composed class implementation can be replaced with an enhanced version. 
  • The object members can be changed at runtime for the dynamic change of the program’s behavior with the use of a composition relationship.

Limitations of composition in Java:

There are a few drawbacks of using composition in Java. The main disadvantage of the object composition is that it is harder for the user to understand the behavior of the implemented system just by pondering over the source code. A system that uses object composition is highly dynamic in nature. So, understanding the functioning of the systems that use object composition requires a deeper analysis of the source code and running the code to witness the functioning and cooperation between the individual objects in the source code. 

If you’re interested to learn more about Java, full-stack software development, check out upGrad & IIIT-B’s  Executive PG Programme in Software Development – Specialisation in Full Stack Development  which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Profile

Pavan Vadapalli

Something went wrong

Our Popular Software Engineering Courses

Full Stack Development

Our Trending Software Engineering Courses

  • Master of Science in Computer Science from LJMU
  • Executive PG Program in Software Development Specialisation in Full Stack Development from IIIT-B
  • Advanced Certificate Programme in Cyber Security from IIITB
  • Full Stack Software Development Bootcamp
  • Software Engineering Bootcamp from upGrad

Popular Software Development Skills

  • React Courses
  • Javascript Courses
  • Core Java Courses
  • Data Structures Courses
  • ReactJS Courses
  • NodeJS Courses
  • Blockchain Courses
  • SQL Courses
  • Full Stack Development Courses
  • Big Data Courses
  • Devops Courses
  • NFT Courses
  • Cyber Security Courses
  • Cloud Computing Courses
  • Database Design Courses
  • Crypto Courses
  • Python Courses

Explore Free Courses

Study Abroad Free Course

Learn more about the education system, top universities, entrance tests, course information, and employment opportunities in Canada through this course.

Marketing

Advance your career in the field of marketing with Industry relevant free courses

Data Science & Machine Learning

Build your foundation in one of the hottest industry of the 21st century

Management

Master industry-relevant skills that are required to become a leader and drive organizational success

Technology

Build essential technical skills to move forward in your career in these evolving times

Career Planning

Get insights from industry leaders and career counselors and learn how to stay ahead in your career

Law

Kickstart your career in law by building a solid foundation with these relevant free courses.

Chat GPT + Gen AI

Stay ahead of the curve and upskill yourself on Generative AI and ChatGPT

Soft Skills

Build your confidence by learning essential soft skills to help you become an Industry ready professional.

Study Abroad Free Course

Learn more about the education system, top universities, entrance tests, course information, and employment opportunities in USA through this course.

Suggested Blogs

AWS Cloud Practitioner Salary In India 2023 [Beginners to Experienced]

by Pavan Vadapalli

07 Sep 2023

WordPress Developers Salary in India in 2023

by Rohit Sharma

02 Sep 2023

23 Exciting Software Development Project Ideas & Topics for Beginners [updated 2023]

by Rohan Vats

31 Aug 2023

Top 9 Important Coding Interview Questions & Answers 2023 [For Freshers & Experienced]

30 Aug 2023

Software Engineering Interview Questions & Answers [For Freshers & Experienced]

29 Aug 2023

12 Interesting Computer Science Project Ideas & Topics For Beginners [Latest 2023]

28 Aug 2023

AWS Lambda Tutorial for Beginners: Complete Tutorial

17 Aug 2023

What is Composition in Java? With Examples

What is Composition in Java? With Examples

Basics of Association in Java:

Association can be defined in Java as an interconnection between two individual classes using their distinct objects. The types of relationships managed by Java association are:

  • One-to-one: There exists only a single derived class for each parent class.
  • One-to-many: A single parent class may have more than one child class. 
  • Many-to-one: A single child class may be associated with more than one superclass.
  • Many-to-many: A number of parent classes may be associated with a single child class and more number of child classes may be associated with a single parent class. 

Once the relationship is established, the derived classes communicate with the respective base classes to reuse their characteristics and properties. There are two types of association in Java. They are aggregation and composition.

Aggregation in Java is a more generalized process as compared to the composition. These forms are based on the type of relationship supported between the classes. 

Introduction to Composition in Java:

A designing technique in Java that implements a Has-A relationship is referred to as composition. The process of inheritance is used to reuse the code. The composition in Java can be accomplished using an instance variable referring to other objects. If an object constitutes another object in such a way that the constituent object cannot exist without the survival of the main object, the kind of relationship is referred to as the composition. To be more specific, the composition is an aspect that describes the reference among two or more classes with the help of instance variables. Here, the instance should be created before using the instant variables. Let us take an example of a Library for a clear understanding of the concept ‘composition’.

Ads of upGrad blog

There exist numerous books in a library. Each book has separate authors and titles. The library should also have a reference list of books in it. The library also has several books related to the same subject or diverse subjects. Here, the library corresponds to the main class and the books can be related to the derived class. The association or the relationship between the books and the library can be regarded as composition. This is because the class “Books” is completely dependent on the class library. For instance, if the library is destroyed, then all the books in it are also destroyed. 

Check out our  free technology courses  to get an edge over the competition.

Explore our Popular Software Engineering Courses

A detailed description of composition in java:.

The Composition is a form of Java association. The two communicating classes are strongly interlinked, where the derived class is completely dependent on the parent class. The independent existence of the derived class is not possible in this case. For example, an engine without a car cannot exist independently. This association type is highly restricted as compared to the aggregation. Composition is a design technique and should not be confused with a Java feature. 

The Composition can be used to model objects that have other objects as their constituent members. There exists the has-a relationship between these objects. In this association type, one object contains the other object. Hence, the constituent object is completely dependent on the main object for its survival. So, if the containing object is ruined, the constituent object is also affected. Therefore, the composition relationship can be viewed as a part of the whole relationship in which the existence of the part without the whole is not possible. In other words, the part is automatically deleted on the deletion of the whole. This implies that the whole has a firm relationship with the part. 

Learn  Software Development Courses  online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.

In-Demand Software Development Skills

Why prefer composition over inheritance .

  • Classes should use composition instead of inheritance from a parent class to enable polymorphic behavior and code reuse. According to the design concept, the composition should be preferred over inheritance to get a better level of design flexibility. 
  • One justification for choosing composition in Java is the lack of support for multiple inheritances. Since Java only allows for the extension of a single class, Reader and Writer functionality is required if you require multiple features, such as the ability to read and write character data into files. Having them as private members simplifies your task, and this is what is meant by composition.
  • Flexibility is another factor that makes composition superior to inheritance. If you use composition, you have the flexibility to swap out an outdated and improved Composed class implementation. Utilizing the comparator class, which offers features for comparison, is one example.
  • The ability to reuse code is provided by both composition and inheritance. However, inheritance has the drawback of breaking encapsulation. If the subclass’s function depends on the superclass’s action, it suddenly becomes fragile. Sub-class functionality may become unusable when the behavior of the super-class changes without any change on the part of the sub-class.
  • Multiple object-oriented design patterns from Gang of Four: Elements of Reusable Object-Oriented Software, listed in the timeless classic Design Patterns, favor composition over inheritance. The strategy design pattern serves as the finest example of this, using composition and delegation to alter the Context’s behavior without altering the context code. Because Context relies on composition to carry strategy instead of inheriting it, it is easy to have a new implementation of strategy at run-time.

Composition In Java Example

The types of association used to depict the link between two classes are aggregation and composition in java . In the case of composition, If an existing university object is destroyed, all of the department objects will also be destroyed automatically because there is no way for dependent objects to exist without an existing university object. This strong association between the objects is what is meant by the term composition.

How Does Composition Work in Java?

Since the PART-OF type of relation between two entities is implemented using composition, one of the entities is referred to as a container and the other as a composed entity.  The ability to utilize this class as a composite entity in other container classes encourages code reuse. A composition in Java example can include a container class for an engine being a car, a two-wheeler, etc.

Both have dependencies on one another since the combined class is a component of a container entity. However, a composed class can still be void; for example, a car need not be required to have an engine. As a result, the container class serves as the sole source of existence for the composed class. PART-OF relation is also referred to as a subclass of HAS-A relation because Composition is a type of association. Composition assists in establishing a relationship between two entities that are interdependent without the use of inheritance in this way.

How is inheritance different from composition in Java?

It is important to note that the functionality of inheritance can be accomplished using composition in Java as well. Though both inheritance and composition are used to offer reusability of the code by the relating class, there are subtle differences between these two. The main difference between the two processes is that composition is a technique of design, unlike inheritance which is a Java feature. Other major differences between the two are listed in the table below.

Differences between Aggregation and Composition:

Read our popular articles related to software development, advantages of using composition in java:.

  • Composition facilitates the reuse of the Java code.
  • Though multiple inheritances are not supported by Java, the gap can be filled in by this design technique.
  • With the use of composition, a class can be tested for ability in a better manner.
  • The code is made more flexible with the use of composition. The composed class implementation can be replaced with an enhanced version. 
  • The object members can be changed at runtime for the dynamic change of the program’s behavior with the use of a composition relationship.

Limitations of composition in Java:

There are a few drawbacks of using composition in Java. The main disadvantage of the object composition is that it is harder for the user to understand the behavior of the implemented system just by pondering over the source code. A system that uses object composition is highly dynamic in nature. So, understanding the functioning of the systems that use object composition requires a deeper analysis of the source code and running the code to witness the functioning and cooperation between the individual objects in the source code. 

If you’re interested to learn more about Java, full-stack software development, check out upGrad & IIIT-B’s  Executive PG Programme in Software Development – Specialisation in Full Stack Development  which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Profile

Pavan Vadapalli

Something went wrong

Popular Software Development Skills

  • React Courses
  • Javascript Courses
  • Core Java Courses
  • Data Structures Courses
  • ReactJS Courses
  • NodeJS Courses
  • Blockchain Courses
  • SQL Courses
  • Full Stack Development Courses
  • Big Data Courses
  • Devops Courses
  • NFT Courses
  • Cyber Security Courses
  • Cloud Computing Courses
  • Database Design Courses
  • Crypto Courses
  • Python Courses

Our Trending Software Engineering Courses

  • Master of Science in Computer Science from LJMU
  • Executive PG Program in Software Development Specialisation in Full Stack Development from IIIT-B
  • Advanced Certificate Programme in Cyber Security from IIITB
  • Full Stack Software Development Bootcamp
  • Software Engineering Bootcamp from upGrad

Our Popular Software Engineering Courses

Full Stack Development

Explore Free Courses

Law

Kickstart your career in law by building a solid foundation with these relevant free courses.

Marketing

Advance your career in the field of marketing with Industry relevant free courses

Data Science & Machine Learning

Build your foundation in one of the hottest industry of the 21st century

Management

Master industry-relevant skills that are required to become a leader and drive organizational success

Technology

Build essential technical skills to move forward in your career in these evolving times

Career Planning

Get insights from industry leaders and career counselors and learn how to stay ahead in your career

Suggested Blogs

How to Add Two Numbers in Java?

by Pavan Vadapalli

05 Jun 2023

Understanding Constructor Chaining in Java with Examples & Implementation

04 Jun 2023

Top 20 Must Need Java Full Stack Developer Skills in 2023

03 Jun 2023

10 Best Backend for React in 2023

02 Jun 2023

Multithreading in C#: Benefits, Basics & Best Practices

01 Jun 2023

How to Read Environment Variables in Node.js? Why Use, Best Practices

Javatpoint Logo

  • All Differences
  • IT Differences
  • Medical Differences
  • Science Differences
  • Interview Q

Differences

JavaTpoint

The composition gives us the better way of reusing the code, and at the same time, it protects the class that we are reusing from any of its clients. Inheritance is mainly important when we have to create a class from the same family.

Youtube

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h [email protected] , to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • Graphic Designing
  • Digital Marketing
  • On Page and Off Page SEO
  • Content Development
  • Corporate Training
  • Classroom and Online Training

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected] . Duration: 1 week to 2 week

RSS Feed

Association, Composition and Aggregation in Java

Java Course - Mastering the Fundamentals

Introduction

Relationships between classes are crucial in object-oriented programming. Just as the concepts like classes and objects in object-oriented programming are built to model real-world entities, the relationships between classes in object-oriented programming are built to model the relationships between real-world entities, that these classes represent.

In a way, almost everything that we see in the real world can be viewed as a bunch of objects and the relationships/associations between them.

Classes as individual entities( without any relations between them ) are impractical in object-oriented programming because then we would not be able to model the relationships that exist between real-life entities.

A student is called a student because he studies in a school/college. Here both student and college entities can be modeled as two individual classes with a relation of client-provider (wherein college “provides” education to the student) between them. Similarly, there would be no concept of the employee in real life without the existence of an organization that employs individuals, thus an organization is associated with an employee(here the relation is ‘employment’).

Here the Employee and Organization can be modeled as two distinct classes in OOPS with a relation of employment. So understanding how these associations work in object-oriented programming is something every programmer must be aware of, which we shall cover in the further sections of this article.

Association in Java

Association, in general terms, refers to the relationship between any two entities. Association in java is the relationship that can be established between any two classes. These relationships can be of four types:

One-to-One relation

One-to-many relation

Many-to-one relation

Many-to-many relation

To illustrate, let’s take two classes, Professor class, and Department class. Below are the type of relationships/associations that can be possible between them

  • One professor can only be assigned to work in one department. This forms a one-to-one association between the two classes.
  • One professor can be assigned to work in multiple departments. This is a one-to-many association between the two classes.
  • Multiple professors can be assigned to work in one department. This forms a many-to-one association between the two classes.
  • Multiple professors can be assigned to work in multiple departments. This is the many-to-many association between the two classes.

types of association in java

  • So one object will be able to access the data of another object. For example, A professor entity modeled as an object would be able to access/know the names of all the departments he works at. And a department object can be able to access/know the names/details of all the professors that work in it.
  • Functionality/Services of one object can be accessible to another object. For example, A professor who is trying to enroll in a department can be able to verify whether a department he wants to join has a vacancy. This service(programmatic method/function) to find whether there’s a departmental vacancy can be provided by the Department class which the Professor class can access.

Example program to illustrate one-to-many Association between Department class and Professor class in Java:

The program is quite simple and straightforward. Below is a detailed explanation of how this works:

  • Main: Where objects are created and actual program functionality is written
  • Professor: Has the variables and methods related to professor class
  • Department: Has the variables and methods related to department class
  • In the Professor Class, We have defined a variable name to store the name of the professor, and we wrote a constructor Professor() that assigns the name of the professor during object creation and a method getName() to fetch the name of the professor.
  • In the Department Class, we have defined a variable name to store the name of the department and a list of staff to store the list of Professor objects( professors that are working in the department ). We wrote a constructor Department() that assigns the name of the department during object creation and three methods. One is getName()to fetch the name of the department. Two is setStaff() to store the list of staff(professor) objects and Three is getStaff() to fetch the list of staff/professor names (professors that are working in the department)
  • Created two objects for Professor class and one object for Department class
  • Next, create a list to store the objects of type Professor,
  • Add the two newly created objects of type Professor to the list. The objects were assigned names “Arun Kumar” & “Rahul Yadav” at their time of creation.
  • The department name is assigned as “CSE”
  • Add the created staff list to CSE department using setStaff() method;
  • Display the stored variables of department name and the list of names of department staff as output.

The classes Professor and Department are meaningfully interacting with each other, which determines their association. And the relation type here is one-to-many, as one department is related to multiple professors.

Forms of Association in Java

Before we dive into the forms of Association in java, let us briefly explore the types of object relationships that can exist in OOPs. There can be two types of relationships in OOPs:

1. IS-A (Inheritance)

The IS-A relationship is nothing but Inheritance. The relationships that can be established between classes using the concept of inheritance are called IS-A relations.

Ex: A parrot is-a Bird. Here Bird is a base class, and Parrot is a derived class, Parrot class inherits all the properties and attributes & methods (other than those that are private) of base class Bird, thus establishing inheritance(IS-A) relation between the two classes.

The HAS-A association on the other hand is where the Instance variables of a class refer to objects of another class. In other words, one class stores the objects of another class as its instance variables thereby establishing a HAS-A association between the two classes.

2. HAS-A (association)

Note: The example program for the association we have discussed in the above section is a HAS-A association.Because Department class is storing the objects of Professor class as its instance variable staff ( the Listwhich is storing a list of Professors class objects). And a Department class object can access these stored Professor objects to store/retrieve information from Professor Class, thereby creating an association between the two classes.

There are two forms of Association that are possible in Java:

a) Aggregation

b) Composition

Aggregation:

Aggregation in java is a form of HAS-A relationship between two classes. It is a relatively more loosely coupled relation than composition in that, although both classes are associated with each other, one can exist without the other independently. So Aggregation in java is also called a weak association. Let us look at a simple aggregation example to understand this better.

Example : Consider the association between a Country class and a Sportsperson class. Here’s how it is defined

  • Country class is defined with a name and other attributes like size, population, capital, etc, and a list of all the Sportspersons that come from it.
  • A Sportsperson class is defined with a name and other attributes like age, height, weight, etc.

In a real-world context, we can infer an association between a country and a sports person that hails from that country. Modeling this relation to OOPs, a Country object has-a list of Sportsperson objects that are related to it. Note that a sportsperson object can exist with his own attributes and methods, alone without the association with the country object. Similarly, a country object can exist independently without any association to a sportsperson object. In, other words both Country and Sportsperson classes are independent although there is an association between them. Hence Aggregation is also known as a weak association.

Another point to note is that here, the Country object has-a Sportsperson object and not the other way around, meaning the Country object instance variables store the Sportsperson objects(This will be clear when we look at the java program in the next section), so the association is one-sided. Thus Aggregation is also known as a unidirectional association.

relation diagram in java aggregation

Explanation:

  • A Country class is defined with a variable to store its name and another list of “sportPersons” variable to store the objects of SportPerson.
  • A constructor is defined in Country class to assign the name of the country during object creation
  • Three methods getSportPersons() and setSportPersons() and getName() are defined to set or get the list of sportspersons and to get the name of the country.
  • A SportPerson class is defined with a variable name to store its name and a constructor to assign the name during object creation
  • A method getName() is defined in the SportPerson class to get the name of the sportsperson.
  • The implementation in the Main class is pretty straightforward. Three SportPerson objects are created and a Country object is created. All the three SportPerson objects are added to the newly created list.
  • This is the logical idea behind Aggregation, Sportsperson Class objects can exist independently of the Country class object.
  • if Country object is to be deleted, it has no effect on the SportPerson and vice-versa.
  • Thus Aggregation helps in code reusability. Since classes exist independently, The same classes can be reused to create associations with other classes, without having to modify an existing class, or without causing any issues to existing associations.

Composition:

Composition in java is a form of relation that is more tightly coupled. Composition in java is also called Strong association. This association is also known as Belongs-To association as one class, for all intents and purpose belongs to another class, and exists because of it. In a Composition association, the classes cannot exist independent of each other. If the larger class which holds the objects of the smaller class is removed, it also means logically the smaller class cannot exist. Let us explore this association clearly with an example

Example : The association between College and Student. Below is how it is defined.

  • College class is defined with name and the list of students that are studying in it
  • A Student class is defined with name and the college he is studying at.

Here a student must be studying in at least one college if he is to be called Student. If the college class is removed, Student class cannot exist alone logically, because if a person is not studying in any college then he is not a student.

relation diagram in java composition

  • Student class is defined with name and constructor to set the name during object creation
  • A method getName is defined in Student class to get the name of the student
  • College class is defined with name and list of students that are studying in it.
  • A constructor in College class is defined to set the name of the college during the object creation. A method getName is defined to get the name of the college and getStudentList is defined to get the names of the students studying in that college.
  • The method setStudentList is defined, which created three students’ objects inside the College class and assigned them to the college studentList.So here, the Student class objects are created and stored internally in the College class, which creates a tightly bound association between the College and Student classes. Because, if College class is removed, all student objects are removed as well.
  • All the students are to be part of the class, no student can exist independently. And the result is outputted.
  • Note here that no single student can exist without a college, but a college can exist without the student. Student is the dependent class.

Difference between association, aggregation, composition in Java

Association in java is one of the types of relations between classes. It has two forms Aggregation(HAS-A) and Composition(Belongs-to). Aggregation is a relatively weak association, whereas Composition is a strong association. Composition can be called a more restricted form of Aggregation. Aggregation can be called the superset of Composition, since all Compositions can are Aggregations but, not all Aggregations can be called Composition.

difference between association aggregation composition in java

Below are the primary differences between the forms of Association, Composition and Aggregation in java:

We have reached the end of the article. Below are few real-world examples that you can explore to understand the associations between them:

  • Association between Mobile store and mobiles
  • Association between Car and Engine
  • Association between Library and Books
  • Association between Institute, student and department
  • Association between Building and rooms
  • Association between Band and Musician

Understanding how the different forms of association work give us the ability to write code that is closely relevant and practical in the real world. Please let us know if you face any difficulty in understanding this article. For any queries do reach out to me on Linkedin

Scientech Easy

Composition in Java | Example Program

Composition in Java is one of the core concepts of object-oriented programming. It is different from inheritance .

Inheritance is defined as Is-A relationship whereas, composition is defined as Has-A relationship. Both composition and inheritance are design techniques and can be used for the purpose of code reusability.

Composition is a more specialized form of aggregation . In other words, it is a more restrictive and strong form of aggregation.

Java composition differs from aggregation is that aggregation represents a Has-A relationship between two objects having their own lifetime, but composition represents a Has-A relationship that contains an object that cannot exist on its own.

In other words, child object does not have its own lifetime. If the parent object is destroyed, the child object will also be destroyed. The child object cannot exist without the existence of its parent object.

In simple words, a composition can be defined as if a parent object contains a child object and the child object cannot exist on its own without having the existence of parent object, it is called composition in java.

It can be achieved by using an instance variable that refers to another object. Let’s understand the basic meaning of java composition with help of realtime examples.

Realtime Example of Composition in Java

1. We live in a house. House can have many rooms. But there is no independent life of room and it cannot also associate to two different houses.

If we destroy the house, the room will be automatically destroyed. So, we can say that a room is PART-OF the house.

2. Another real-time example of java composition is “Car and Engine”. A car has an engine. In other words, an engine is a PART-OF car. Here, a car is a whole, and engine is a part of that car.

Program code 1:

In this example, we have created a class Engine that contains two private attributes: type (string) and horsePower (integer). It has a constructor that takes two parameters, type and horsePower, and initializes the attributes with these values. In addition to it, there are getter and setter methods for both attributes to retrieve and update their values.

Then, we have created a class Car containing two private attributes: name (string) and engine (of class type Engine). The class has a constructor that takes a name and an engine object as parameters.

The name attribute is assigned the provided name, and the engine attribute is assigned the provided engine object. The class contains getter methods for both attributes to retrieve their values.

We have defined a class Test that contains the main method, which serves as the entry point for the program. Inside the main method, we have created an instance of the Engine class by passing the values “Petrol” and 300 to its constructor.

Then, we have created an instance of the Car class by passing the values “Alto” and the previously created Engine instance to its constructor. This shows the concept of composition, where the Car class contains an instance of the Engine class as one of its attributes.

At last, the program code prints out the name of the car, type of engine, and horse power of the engine using the getter methods of the Car and Engine classes.

Features of Composition in Java

There are several important features about java composition that are as follows:

1. Composition represents a has-a relationship in java. In other words, it represents PART-OF relationship.

2. It is a more restrictive form of aggregation.

3. In composition, both the entities are associated with each other.

4. A composition between two entities happens when an object (in other words, parent object) contains a composed object ( in other words, child object), and the composed object cannot exist without the existence of that object.

For example, a library contains a number of books on the same or different subjects. If the library gets destroyed for any reason, all books placed within that library will be destroyed automatically. That is, books cannot exist without a library of school or college.

5. It can be achieved by using an instance variable that refers to other objects.

Advantages of using Composition over Inheritance

There are several benefits of using composition in java over inheritance. They are as follows:

1. Composition is better than inheritance because it allows to reuse of code and provides visibility control on objects.

2. Java doesn’t allow multiple inheritance but by using composition we can achieve it easily.

3. Composition grants better test-ability of a class.

4. By using composition, we can easily replace the implementation of a composed class with a better and improved version.

5. Composition allows the changing of member objects at run time so that we can dynamically change the behavior of our program.

Hope that this tutorial has covered all the important points related to composition in Java with example programs. I hope that you will understand the basic concepts of composition. In the next, we will understand the basic differences between association, aggregation, and composition in Java with examples. Thanks for reading!!!

⇐ Prev Next ⇒

IMAGES

  1. class

    what is composition java

  2. Association In Java

    what is composition java

  3. Mapping Composite Value Types

    what is composition java

  4. Object-Oriented Programming Principles in Java: OOP Concepts for Beginners

    what is composition java

  5. Composition Vs Aggregation in Java

    what is composition java

  6. Java Composition

    what is composition java

VIDEO

  1. Java -2 Programming and Types

  2. Pantun

  3. 16 Java Intro Summary

  4. JAVA LIBRARIES TOPIC #java ....java.lang, java.util, and java.math

  5. Difference Between composition and aggregation in java

  6. CLASS AND OBJECT IN JAVA FULL EXPLANATION WITH HEAP AND STACK MEMORY

COMMENTS

  1. Composition in Java

    Composition in Java. The Composition is a way to design or implement the "has-a" relationship. Composition and Inheritance both are design techniques. The Inheritance is used to implement the "is-a" relationship. The "has-a" relationship is used to ensure the code reusability in our program. In Composition, we use an instance variable that refers to another object.

  2. Composition in Java

    The composition is a design technique in java to implement a has-a relationship. Java Inheritance is used for code reuse purposes and the same we can do by using composition. The composition is achieved by using an instance variable that refers to other objects.

  3. Composition, Aggregation, and Association in Java

    Composition Composition is a "belongs-to" type of relationship. It means that one of the objects is a logically larger structure, which contains the other object. In other words, it's part or member of the other object. Alternatively, we often call it a "has-a" relationship (as opposed to an "is-a" relationship, which is inheritance ).

  4. OOP Concepts for Beginners: What is Composition?

    Composition is one of the fundamental concepts in object-oriented programming. It describes a class that references one or more objects of other classes in instance variables. This allows you to model a has-a association between objects. You can find such relationships quite regularly in the real world.

  5. java

    They are absolutely different. Inheritance is an "is-a" relationship. Composition is a "has-a".. You do composition by having an instance of another class C as a field of your class, instead of extending C.A good example where composition would've been a lot better than inheritance is java.util.Stack, which currently extends java.util.Vector.This is now considered a blunder.

  6. Composition in Java Example

    Composition in java is the design technique to implement has-a relationship in classes. We can use java inheritance or Object composition in java for code reuse. Composition in Java Java composition is achieved by using instance variables that refers to other objects. For example, a Person has a Job.

  7. Composition vs Inheritance

    Composition Composition is the design technique in object-oriented programming to implement has-a relationship between objects. Composition in java is achieved by using instance variables of other objects. For example, a person who has a Job is implemented like below in java object-oriented programming.

  8. java

    Composition. Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition. Concrete examples in Java from here and here. Dependency

  9. Association, Composition and Aggregation in Java

    Composition and Aggregation are the two forms of association. Example: Java import java.io.*; import java.util.*; class Bank { private String name; private Set<Employee> employees; Bank (String name) { this.name = name; } public String getBankName () { return this.name; } public void setEmployees (Set<Employee> employees) {

  10. Composite Design Pattern in Java

    The composite pattern is meant to allow treating individual objects and compositions of objects, or "composites" in the same way. It can be viewed as a tree structure made up of types that inherit a base type, and it can represent a single part or a whole hierarchy of objects. component - is the base interface for all the objects in the ...

  11. Java inheritance vs. composition: How to choose

    Inheritance and composition are two programming techniques developers use to establish relationships between classes and objects. Whereas inheritance derives one class from another, composition...

  12. Java Composition

    June 22, 2023 This Java Composition tutorial explains what is Composition and Aggregation in Java and the differences between them: In the last couple of tutorials, we discussed inheritance in Java in detail. Inheritance in Java is a type of "IS-A" relationship which indicates that one object 'is a kind of' another object.

  13. What is Composition in Java With Examples

    What is Composition in Java With Examples Arjun Mathur 9th Apr, 2021 7 Mins Java is a versatile language that supports object-oriented programming and code reusability with building relationships between two classes. There are two types of relationships or associations in Java used to reuse a code and reduce duplicity from one class to another.

  14. Getting Started with Composition in Java

    Composition in Java. It also occurs when a class references one or more objects of other classes in a single instance. For example, a Class Car is a composition of class Engine and class wheels and a Class Body is a composition of the class Heart, class Stomach, etc.

  15. What is Composition in Java? With Examples

    Advantages of using Composition in Java: Composition facilitates the reuse of the Java code. Though multiple inheritances are not supported by Java, the gap can be filled in by this design technique. With the use of composition, a class can be tested for ability in a better manner. The code is made more flexible with the use of composition.

  16. Inheritance and Composition (Is-a vs Has-a relationship) in Java

    1. Overview. Inheritance and composition — along with abstraction, encapsulation, and polymorphism — are cornerstones of object-oriented programming (OOP). In this tutorial, we'll cover the basics of inheritance and composition, and we'll focus strongly on spotting the differences between the two types of relationships. 2.

  17. Difference Between Aggregation and Composition in Java

    Composition is a "belong-to" type of relationship in which one object is logically related with other objects. It is also referred to as "has-a" relationship. We can understand has-a or belong-to by using the following example: A classroom belongs to a school, or we can say a school has a classroom.

  18. What is Composition in Java? With Examples

    A designing technique in Java that implements a Has-A relationship is referred to as composition. The process of inheritance is used to reuse the code. The composition in Java can be accomplished using an instance variable referring to other objects.

  19. Difference between Inheritance and Composition in Java

    Let's first see the brief description of inheritance and composition in Java. Inheritance Inheritance is an important part of OOPs (Object Oriented programming system). In Java, it is a mechanism in which one object acquires all the properties and behaviors of a parent object.

  20. Association, Composition and Aggregation in Java

    Association in java is one of the types of relations between classes. It has two forms Aggregation (HAS-A) and Composition (Belongs-to). Aggregation is a relatively weak association, whereas Composition is a strong association. Composition can be called a more restricted form of Aggregation.

  21. Composition in Java

    In simple words, a composition can be defined as if a parent object contains a child object and the child object cannot exist on its own without having the existence of parent object, it is called composition in java. It can be achieved by using an instance variable that refers to another object.

  22. Association, Aggregation, and Composition

    Composition in java is a concept which states that there lies a strong relationship between the two objects associated with the given two classes. It is also said to fulfill the "has-a" relationship between the two classes. In composition, the parent class owns the child class which means the child class cannot be a stand-alone entity. ...