×

Composition in Java

Composition

Java uses the composition method to implement a has-a connection. Composition allows us to reuse code in the same way that Java inheritance does. The "is-a" relationship is implemented using the inheritance. In composition, we apply the "has-a" relationship to ensure that the code can be reused. Utilizing an instance variable that makes references to other objects, the composition is accomplished. It is referred to as composition when one item contains another and the enclosed object cannot exist without the other. To put it another way, composition refers to a relationship between two or more classes that contain instance variables, and an instance must be constructed before it is used.

When one element includes another and that other object is entirely dependent upon it, a composition relationship between the two objects is established. It should be impossible for the contained object to function without the parent object. To put it simply, we may say that it is a method for describing the relationship between two or more classes. And to do that, we make use of the instance variable, which must first be defined.

Key Points

  • A component of a relationship is represented by the composition.
  • In the composition, both things are connected to one another.
  • When an item has a composed object and the composed object is dependent on another entity to function, this is when two entities are said to be composed.
  • Give composition preference over inheritance.
  • With an instance variable that makes references to other objects, the composition is done.

A narrower version of aggregation is the composition. It is impossible for one class to work without another one in composition since it depends on and contains another class.

Implementation

The Java programming language uses the keyword "final" to express composition. This is because that the 'Parent' object, that makes a component object 'final,' may assume it to be accessible and work.

Lets go through a small example to know how the syntax is written and understand the program flow

Syntax

public class Parent class name
 {
           private final Child class name child class object; 
    public Parent class name ()
   {
    child = new Child ();
   }
 }
 class Child class name
 {
private String type;
 }

Main.java

 public void BeginEngine (){
        System.out.println(“The bike has Started.”);
    }
    public void TerminateEngine (){
        System.out.println(“The bike has Stopped.”);
    }
} 
class MotorBike {
    private String colour;
    private int maxi_Speed;
    public void bikeDetails(){
        System.out.println(“Bike Colour= “+colour + “; Maximum Speed= ” + maxi_Speed);
    }
    //Setting colour of the bike
    public void setColour(String colour) {
        this.colour = colour;
    }
    //Setting maximum bike Speed
    public void setMaxiSpeed(int maxi_Speed) {
        this.maxi_Speed = maxi_Speed;
    }
} 
Class Yamaha extends Bike{
    public void YamahaStart(){
        BikeEngine Yamaha_Engine = new BikeEngine(); //composition
        Yamaha_Engine.startEngine();
        }
} 
public class Main {
    public static void main(String[] args) {   
        Yamaha YamahaR15 = new Yamaha();
        YamahaR15.setColour(“Red”);
        YamahaR15.setMaxSpeed(100);
        YamahaR15.bikeDetails();
        YamahaR15.YamahaStart();
    }
}

Output:

Bike colour = Red; Maximum speed = 100
The bike has started

The result, which displays the specifications of the Yamaha R15 motorcycle, is generated using composition.

Advantages

The below advantages can be gained by using Java's composition technique:

  • It is very convenient to choose object composition over the class inheritance. Code reusability and polymorphism can also be achieved using composition technique.
  • The composition is adjustable, allowing you to modify the function of each object and update the class execution dynamically.
  • In composition technique minimum number of classes are used in program code.
  • The conceptually accurate relationship among classes is "HAS-A," not "IS-A."
  • Improve working testing process provided by composition in Java is very helpful for test-driven development.
  • By combining many objects as one, it is feasible to create "multiple inheritances" in programming languages like java.
  • Neither function nor object name differences exist in composition.

Disadvantages

  • The composition technique is not useful or not the solution in every scenario.
  • Due to inheritance, almost any situation in which an instance of the base class would be appropriate can also be applied to an instance of the derived type. Composition restricts such behavior.
  • Classes often derive from internal improvements that compositions at run-time do not.
  • Only when an object is the parent of another, the composition make good sense. Just like when a human being owning a dog as a pet.

Related Topics

Get year from date in Java

The getYear() method of the Java date class returns a number calculated by deducting 1900 from the year that contains or starts with the instant in time represented by this...

4 minutes read.

Stock Span Problem Using Stack in Java

The stock span problem is an issue in finance where we must determine a stock’s price span over all N days given a set of N daily price quotes. The...

6 minutes read.

Java String hashCode() method

Java String hashCode() method returns hash code for current String. hash code for string object is computed as s[0]*31^(n - 1) + s[1]*31^(n - 2) + ... + s[n - 1] Using int...

2 minutes read.

XOR of Array Elements Except Itself in Java

A lot of the biggest IT organisations, including The Google, Amazon, TCS, and The Accenture, etc., question about this issue in their interview processes. By addressing the issue, one hopes to assess...

5 minutes read.

Determine the Upper Bound of a Two-Dimensional Array in Java

Multi-Dimensional Array Multi-faceted exhibits in Java are regular and can be named various clusters. Information in a two-layered bunch in Java is put away in 2D even structure. A two-layered collection...

3 minutes read.

Java Math log() Method

The log() method of Math class returns the natural logarithmic value for the specified double argument. Syntax: public static double log(double a) Parameters: The parameter ‘a’ represents the value. Return Value: The log() method returns the...

1 minute read.

Quick Sort in Java

Quick Sort in Java Like merge sort, quick sort also uses the divide and conquer approach to sort the given array or list. In quick sort, the sorting of an array...

6 minutes read.

Program to find the duplicate characters in a string

Problem statement You have given with a string and your task is to find out the repeated characters from the string and print them. If no character is repeated, then you...

2 minutes read.

Zigzag Traversal of Binary Tree in Java

In this article, you will be acknowledged about the zigzag traversal of binary tree in java and the approaches or ways in which the zigzag traversal can be done. Zigzag Traversal A...

10 minutes read.

What is anagram in Java?

In this section will explain what an anagram is in Java and demonstrate how to determine whether or not a text is an anagram. In Java interviews, the anagram Java...

4 minutes read.

How to Convert double to int in Java

The double is a larger data type than int. When we assign a larger type value to a variable of smaller type, then we need to perform the explicit conversion....

2 minutes read.

Computing Digit Sum of all Numbers from 1 to n in Java

In this tutorial, we will discuss various methods to compute the sum of digits of all numbers beginning from 1 to n through a Java program. We will achieve it through...

7 minutes read.

GCD of Different SubSequences in Java

The positive numbers are provided in an array called inArr. The aim is to determine the number of distinct GCDs (Greatest Common Divisors) in each subsequence present in the input...

4 minutes read.

Java Abstraction

Java Abstraction Abstraction is an advanced feature of Java to make it transparent. The main motive behind the abstraction is to deal with ideas, not with events. Abstraction is a process...

4 minutes read.

Interchange Diagonal elements in Java

In this article, you will be very well acknowledged about what is a matrix with an example. You will also be acknowledged about how to interchange the diagonal elements in...

4 minutes read.

Java Iterator

When iterating through, traversing, or retrieving the individual elements of a Collection or Flow object, a Java Cursor is leveraged as an iterator. In Java, there exist three types of...

4 minutes read.

Command Class in Java

We use the command class to run commands against the database. The Command class may find a set of parameter objects for use in sending values to a stored procedure...

3 minutes read.

Snake and Ladder Problem in Java

Find the smallest number of dice throws necessary to reach the destination or last cell from the source or first cell on a snake and ladder board. Essentially, the player...

6 minutes read.

Magic Square in Java

A square with numbers is referred to as a magic square. The numbers in a magic square of order n are arranged to ensure that the sum of all of...

4 minutes read.

Davis Staircase Problem in Java

Davis has several stairs in his home and prefers to ascend one, two, or three steps at a time. As a highly clever youngster, he thinks about how many ways...

3 minutes read.