Java Composition - The Coding Shala

Home >> Learn Java >> Java Composition

Java Composition

Java Composition is a restricted form of Aggregation. In Composition, both the entities are highly dependent on each other. An association is said to composition if an object owns another object and another object cannot exist without the owner object. The composition is a strong type of association. It represents a part-of relationship. For example, A human having a Heart. Here a heart is a part of the human, without A human heart does not exist. Another example of A car and engine object. To move the car engine should be there.
Java Composition - The Coding Shala

Example of Composition in Java

The following example explains the Java Composition:
//Java Example of Composition

class Heart{
    Heart(){
        System.out.println("Heart is working");
    }
}

class Human{
    private final Heart heart;
    
    Human(Heart heart){
        this.heart = heart;
    } 
    
    void Alive(){
        System.out.println("Human is alive");
    }
}

class Main{
    public static void main(String[] args){
        Heart h = new Heart();
        Human human = new Human(h);
        human.Alive();
    }
}
Output:
Heart is working
Human is alive



Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Add two numbers in Scala - The Coding Shala

LeetCode - Number of Good Pairs Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala