Home > Java > javaTutorial > body text

Composition in Java

PHPz
Release: 2024-08-30 16:12:13
Original
796 people have browsed it

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;
}
Copy after login

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);
}
}
Copy after login

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();
}
}
Copy after login

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();
}
}
Copy after login

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 );
}
}
Copy after login

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();
}
}
Copy after login

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!

Related labels:
source:php
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!