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
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");
public String toString()
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");
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);
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.
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.