×

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

System Class in Java

The System class provides features including a way to load files and libraries, standard input, standard output, and errors throughput streams, accessibility to outside defined characteristics and environment variables, and...

3 minutes read.

Java Math nextUp() Method

The nextUp() method of Math class returns the floating-point number adjacent to the argument in direction of the positive infinity. Syntax: public static double nextUp (double d)public static float nextUp (float f) Parameters: The...

2 minutes read.

What’s New in Java 15

Sealed classes are the new concept that was introduced by Java 15. Sealed classes are a preview feature. Most of the features which are released in java 15 are in...

3 minutes read.

Java Worker Class

What is a Worker? A service which executes Work - flow and Activities is referred to as a Worker. On user-controlled hosts, workers are defined and put into action. The Worker...

3 minutes read.

Java String concat() method:

Java String concat() method is used to add the given String to the end of the current String. Syntax: public String concat(String str) Parameter: Str: String to be concatenated at the end of current...

1 minute read.

Java OCR

In this article, you will be acknowledged about what is a tesseract OCR, how it works, what are its used and advantages and disadvantages. Also, you will be able to...

4 minutes read.

Program to Implement FLAMES Game in Java

Friends, Lovers, Affectionate, Marriage, Enemies, and Sibling are all represented by the acronym FLAMES, which also serves as the name of a well-known game. Although, it can be entertaining to...

4 minutes read.

Type Annotations in Java

Only declarations were eligible for annotations in earlier versions of Java. With Java 8, you may now annotate any type use, including types in declarations, generics, and casts: @Encrypted String data; List<@NonNull...

6 minutes read.

Java URL Class with Example

Java URL Uniform Resource Locator To find any resource on the internet, you need to have an address of it. The URL and IP addresses are the pointers used for this purpose....

12 minutes read.

Java String Inbuilt functions

There are different types of inbuilt functions available in the Java String class, all of them are listed below. Char chat At (int index)It outputs the character indicated by the index....

5 minutes read.

Object class in Java

In Java, a class is a file containing the Java byte code. It can essentially specifically be executed on the JVM (Java Virtual Machine), fairly significant. The JVM mostly generally...

6 minutes read.

Interface Program in Java

Interface Program in Java In the previous topic, we discussed that abstraction is possible through the interface and abstract class. An abstract class provides partial to 100% abstraction. 100 %abstraction in...

4 minutes read.

Prime Points in Java

The points that divide an integer into two halves containing a prime number are known as prime points. Printing every prime point of a specific number is the task. Let's...

6 minutes read.

Anonymous Function in Java

A function defined as being unbound from an identifier is called an anonymous function. Because they permit access to variables within the scope of the contained function, these are a...

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.

List all files in a Directory in Java

The list of all files in the directory can be done using Java. You should be aware that a directory may include a subfolder and that subdirectory may also contain some...

3 minutes read.

Undo and Redo Operations in Java

Undo and redo operation are the most widely used operation while dealing with file. In this section, we will discuss how to implement undo and redo operation in Java. Undo Redo...

2 minutes read.

Sleeping Barber Problem in Java

The barbershop in this issue has one barber, one barber chair, and N chairs for customers in the waiting area. We may demonstrate the issue by keeping with the original...

6 minutes read.

How to initialize string array in Java

In this tutorial, we will learn how the string array is initialized in java. The initialization of string array in the java by using the NEW (it creates the object for...

3 minutes read.

Singleton class in Java

What is Singleton class in Java? Singleton means it is one. That means we can create only one instance or object of a class. For example, let us have a class...

3 minutes read.