by Dinesh Thakur Category: Inheritance

Inheritance is suitable only when classes are in a relationship in which subclass is a (kind of) superclass. For example: A Car is a Vehicle so the class Car has all the features of class Vehicle in addition to the features of its own class. However, we cannot always have. is a relationship between objects of different classes. For example: A car is not a kind of engine. To represent such a relationship, we have an alternative to inheritance known as composition. It is applied when classes are in a relationship in which subclass has a (part of) superclass.

Unlike inheritance in which a subclass extends the functionality of a superclass, in composition, a class reuses the functionality simply by creating a reference to the object of the class it wants to reuse. For example: A car has an engine, a window has a button, a zoo has a tiger.

Now consider. the following program that demonstrates the concept of composition

class Date

{
     private int day;
     private int month;
     private int year;
     Date(int dd, int mm,int yy)
     {
       System.out.println("Constructor of Data Class is Called");
       day=dd;
       month=mm;
       year=yy;
     }
     public String toString()
     {
       return (day+"/"+month+"/"+year);
     }
}
   class Employee
{
     private int id;
     private String name;
     private Date hireDate; //object of Data class
     Employee(int num,String n, Date hire)
     {
       System.out.println("Constructor of Employee Class is Called");
       id=num ;
       name=n ;
       hireDate=hire;
     }
     public void display()
     {
       System.out.println("id = "+id);
       System.out.println("Name = "+name);
       System.out.println("Hiredate = "+hireDate);
     }
}
   public class Composition
   {
       public static void main(String[] args)
        {
                Date d = new Date(01,01,2011);
                Employee emp = new Employee(1,"Dinesh Thakur",d);
                emp.display();
        }
  }

Composition in Java Example

In this example, we first define a class Date for maintaining the date information. Then we define a class Employee that not only contains members id, name and display () but also contains a reference variable hireDate to refer objects of class Date as its member, which maintains employee's hiredate.

The statement,

emp.display () ;

on execution will display employee's id, name and the hiredate. The hireDate is obtained with an implicit call to the Date class's toString () method.



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Related Articles