Composition has-a Relationship

Composition has-a Relationship

Composition has-a Relationship

One of the goals of OOP languages is reusability. Java gives good importance for reusability. A method in Java can be called in two ways.

  1. 1. With the objects of the same class (through composition)
  2. 2. With the objects of other classes (through inheritance)

Here we discuss the composition.

Composition has-a Relationship

Output screen of

Before going to composition, let us know how to write the above code and on which name the Java file should be opened. The rule says, in a single source code, if a number of classes exist, only one class can be public. The file name must be of that class which is public. In the code, two classes exist – Bird and Parrot. As Parrot is public, the file opened must be on the name of "". So, open "" file and write the source code and compile as usual as "javac" and execute as "java Parrot".

The Parrot class, in its main() method, created an object of Bird and called Bird's method eat(). Here, Bird and Parrot are no way connected or related (I mean, no inheritance). Just they happened to be in the same folder. This feature we call as "composition". Creating another class object in our class and calling other class methods is known as composition.

Composition has-a Relationship

Composition uses the concept called "has-a" relationship. We say, our class has a object of other class. Parrot "has a " object of Bird. Composition is meant for reusability.

When compiled, we get two .class files – Bird.class and Parrot.class. These classes work independently of each other even though they are coming from a single source file. Any other third class can make use of the methods of either both or any one these classes by composition.

There is one more concept called aggregation which differs slightly from composition. To know their narrow difference see Aggregation and Composition.

14 thoughts on “Composition has-a Relationship

  1. pavan

    class bike {
    public static void petrol() {
    System.out.println(“bikes run with petrol”);

    public class Vehicle {

    public static void main(String args[]) {
    bike b = new bike();


    Hi sir we have a rule from static keyword that we can call static methods with out object but in this program it is giving a compilation error by calling petrol method with out object can u plzz guide me where am wrong??

Leave a Reply

Your email address will not be published. Required fields are marked *