×

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

What is string in Java why it's immutable

String in Java Strings are a series of characters commonly used in Java language, which are considered objects in the Java. To create and manipulate strings, java will provide the String...

4 minutes read.

Upcasting in Java

To know what is Upcasting in Java we should first equip ourselves about what is casting or type casting in Java. Casting The process of providing or replacing a reference variable of...

3 minutes read.

JIT in Java

What is JIT ? JIT stands for " Just in Time Compiler ". It is called "Just in time" because it is called at the very last moment when the interpretation...

5 minutes read.

Binary Strings Without Consecutive Ones in Java

N, an integer, is provided. Our objective is to determine the overall number of strings with length N that do not include successive 1s. Example: Input: 3 Output: 6 Explanation The binary forms of length...

6 minutes read.

Java String intern() method

Java String intern() method returns canonical representation for the String Object. syntax: public String intern() Return: It returns a interned String that to be a pool of unique String. Java String intern() Example 1 public class...

2 minutes read.

Java import packages

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Display List of TimeZone with GMT and UTC in Java

It is vital to establish the right TimeZone in Java code when working with dates for Daylight Saving Time. In this part, we will present the time zones with GMT. TimeZone Those...

5 minutes read.

Pernicious Number in Java

If the number of 1s in a number appearing in the binary representation is the prime number, such a number is known as a pernicious number. A pernicious number always corresponds to...

4 minutes read.

Program to Find Square Root of a Number Without sqrt Method in Java

The Java Math class sqrt () function can be used to determine the square root of a number. In this section, we'll write a Java program to find a number's...

3 minutes read.

Java Identifiers

In Java, the symbolic notations used for identification are called identifiers. Identifiers can be the name for the class, variable name declaration, name of the package, constant name and many...

3 minutes read.

Java Extends keyword

Extends Extends is a keyword which is completely depended on the concept of the inheritance of the java programming language.To understand about of the keyword, we need to learn the concept...

3 minutes read.

Java Integer class

The Integer class wraps a primitive int type value in an object. Its object contains only a single field whose type is int. Methods: The java.lang.Integer class provides several different methods for...

4 minutes read.

Java LinkedHashSet

LinkedHashSet in Java with Example Java LinkedHashSet extends HashSet and Implements the Set interface. It doesn’t contain only duplicate values like HashSet. It also permits the null elements. It maintains the order...

5 minutes read.

How to use Lambda Expression in Java?

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single method interface using an...

4 minutes read.

Enterprise Java Beans

One of the many Java APIs for the common development of corporate software is Enterprise Java Beans (EJB). An EJB, a server-side software component, contains the business logic of an...

4 minutes read.

Upcasting and Downcasting in Java

Type casting in Java is an important and very interesting topic to deal with. But here upcasting and downcasting is somewhat related to typecasting. In normal typecasting, we convert from...

6 minutes read.

Package naming convention in Java

It is conceivable that many programmers will use the same name for various types, given that Java programmers from all over the world create classes and interfaces. For illustration, suppose...

4 minutes read.

Java Integer numberOfTrailingZeros() method

The numberOfTrailingZeros()  method of Java Integer class returns the total number of zero bits following the lowest-order one-bit in the 2’s complement binary representation of the specified int value. Syntax public static...

1 minute read.

Java String toLowerCase() methods

Java String toLowerCase() method is used to convert all the characters of the String into lower case. Syntax: public String toLowerCase()              public String toLowerCase(Locale locale) Returns: It returns Lower...

1 minute read.

Java Extends vs Implements

Java: We known that the java is a pure object oriented programming language. Java programming language consists of many features such as portable, plat form independence, secured, robust, simple, architecture neutral,...

4 minutes read.