Java Composition - The Coding Shala
Home >> Learn Java >> Java Composition
Output:
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.
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(); } }
Heart is working Human is alive
Other Posts You May Like
Comments
Post a Comment