search
HomeJavajavaTutorialComposition in Java

Composition in Java

Aug 30, 2024 pm 04:12 PM
java

Composition is a type of association that is used to represent the “PART-OF” relationship between two objects. Composition in java is a restricted form of another type of association-aggregation where the two entities in a “Has-a” relation have their own existence and are not dependent on each other. In composition, one of the entities is contained in other entities and cannot exist alone. Unlike Inheritance which is used to represent is-a relationship.

For example, there are two classes Car and Engine, Car is composed of an engine object, and the engine entity does not have existed without Car.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Composition in Java

Syntax:

class C1{
// A class represents the dependent entity
}
class C2{
//This class represents the entity that contains the dependent entity by declaring the object of the above class as one of its member variables.
private C1 a;
}

Using the above syntax, we are able to establish the “isPart-Of” relation between the above two entities where C1 depends on the other entity for its existence. Also, it can be illustrated that the existence of a dependent object is optional.

Why Do We Need Composition in Java?

While using inheritance for the representation of 2 entities, we can see, only IS-A relation can exist. But in case two entities contain has-a relation between, then aggregation is required. Aggregation is 2 different types:

1. Association

This is used to represent the relation where 2 entities exist with HAS-A relation, but one is not dependent on others for its existence. Also, it is a unidirectional type of association. For e.g., Bank and Employees are two entities where the single entity of Bank can be related with more than one employee; thus, a bank has one-to-many relations with the employee, but vice versa does not exist.

2. Composition

This is a restrictive type of association used when one of the 2 entities is composed within another container entity. The composed entity cannot exist without a container object. But one can have a null composed entity. Thus it is used to represent PART-OF relation which is bidirectional; thus, both entities are dependent on each other.

How Does Composition Work in Java?

Since composition is used to implement the PART-OF type of relation between two entities, one entity is said to be a container, and the other is a composed entity.  The composed entity is like a complete container object, which has its own properties and operations, thus making a separate entity for it. This also helps in code reuse as this class can be used in other container classes as a composed entity. For e.g., Engine is a composed class, and Car, TwooWheeler, etc., can be container class for it.

Since the composed class is a part of a container entity, both have dependencies on each other. But still, a composed class can be null say Car need not have an engine compulsory. With this, the Composed class is completely dependent on the container class for its existence. Also, since Composition is a type association, thus PART-OF relation is also said to be a subclass of HAS-A relation. This way, Composition helps to implement a relation between two entities dependent on each other without using inheritance.

Example to Implement Composition in Java

Consider the case of Office that is composed of the different lists such as Desk, Meeting Rooms. Desk Object is further composed of a Phone Object as every desk has one desk phone.

Composition in Java

Phone.Java

Code:

package Try;
public class Phone {
private String Model;
private String contactNum;
Phone (String model, String num){
this.Model=model;
this.contactNum=num;
}
public void getPhoneDetails(){
System.out.println("Phone Model "+ this.Model);
System.out.println("Desk Number " + this.contactNum);
}
}

Desk.Java

Code:

package Try;
public class Desk {
private String id;
private String Mid;
private Phone deskNum;
private String personName;
Desk(String id,String mid,Phone contact,String name){
this.id=id;
this.Mid = mid;
this.deskNum=contact;
this.personName=name;
}
public void getDeskDetails(){
System.out.println("Desk Details :-");
System.out.println("Id " + this.id);
System.out.println("Machine ID "+ this.Mid);
System.out.println("Allocated To " + this.personName);
this.deskNum.getPhoneDetails();
}
}

Meeting Room.Java

Code:

package Try;
public class MeetingRoom {
private String name;
private Phone contact;
private String location;
private int numChairs;
private int numTables;
MeetingRoom(String name,Phone contact,String location,int nChairs, int nTables){
this.name=name;
this.contact=contact;
this.location=location;
this.numChairs=nChairs;
this.numTables=nTables;
}
public void getMeetingRoomDetails(){
System.out.println("Meeting Room Details :-");
System.out.println("Name " +this.name);
System.out.println("Location "+ this.location);
System.out.println("Number OF Chairs " + this.numChairs);
System.out.println("Number OF Tables "+this.numTables);
contact.getPhoneDetails();
}
}

Office.java

Code:

package Try;
import java.util.List;
public class Office {
private String offcName;
private List<desk> deskList;
private List<meetingroom> roomList;
private int pantryNum;
public Office(String name , List<desk> dList, List<meetingroom> mList,int pnum){
this.offcName = name;
this.deskList = dList;
this.roomList = mList;
this.pantryNum =pnum;
}
public void getDetails(){
System.out.println("Below are details of "+ offcName +"Office");
for(Desk a:deskList){
a.getDeskDetails();
}
for(MeetingRoom m:roomList){
m.getMeetingRoomDetails();
}
System.out.println("Number Of pantry " + pantryNum );
}
}</meetingroom></desk></meetingroom></desk>

Demo.Java

Code:

package Try;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.ArrayList;
import java.util.List;
public class Demo extends Frame {
public static void main(String[] args){
List<desk> dList =new ArrayList<desk>();
List<meetingroom> mList =new ArrayList<meetingroom>();
Phone p1=new Phone("NOTOROLA","12346");
Phone p2=new Phone("NOTOROLA","35235");
Phone p3=new Phone("BSNL","23233");
Phone p4=new Phone("BSNL","123346");
Desk d1 =new Desk("S121","M12",p1,"Tom");
Desk d2 =new Desk("S122","M14",p2,"Pam");
dList.add(d1);
dList.add(d2);
MeetingRoom m1=new MeetingRoom("Kurukshetra",p3,"Floor_10",10, 2);
MeetingRoom m2=new MeetingRoom("Karnal",p4,"Floor_9",20, 3);
mList.add(m1);
mList.add(m2);
Office o1= new Office("Banglore" , dList,  mList,20);
o1.getDetails();
}
}</meetingroom></meetingroom></desk></desk>

Output:

Composition in Java

Explanation: In the above program, the Office object is composed of a list of Desks and Meeting Room entities, where further Desk and Meeting room is composed of a Phone entity. Here, the Phone is always related to the Desk or Meeting Room object, thus having no existence. Also, Meeting Rooms and Desks have a dependency on Office objects. Here a Single Phone class can be used as a composed entity in the Desk and Meeting Room, thus helps to achieve code reusability.

Conclusion

It is a restrictive type of aggregation used to implement the PART-OF relationship between 2 entities that have bidirectional relation and has the composed entity that does not have existed without the container entity. It is beneficial as any changes made in the composed class do not affect the rest of the code and code reuse.

The above is the detailed content of Composition in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.