We have discussed the concept of inheritance which is a powerful mechanism of reusing code, minimizing data redundancy, and improving the organization of object oriented system. Inheritance is suitable only when classes are in a relationship in which child class is a parent class. For example: A Car is a Vehicle, so the class Car has all the features or properties of class Vehicle and in addition to its own features. However, we cannot always have is a relationship between objects of different classes. Let us say with 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 child class has a parent class.
Unlike Inheritance in which a subclass extends the functionality of a superclass, in composition, a class reuses the functionality by creating a reference to the object of the class it wants to reuse. For example: A car has a engine, a window has a button, a zoo has a tiger.
Composition is a special case of aggregation. In other words, a restricted aggregation is called composition. When an object contains the other object and the contained object cannot exist without the other object, then it is called composition.
Table of Contents
Let us consider the following program that demonstrates the concept of composition.
Step 1: First we create a class Bike in which we declare and define data members and methods:
class Bike { // declaring data members and methods private String color; private int wheels; public void bikeFeatures() { System.out.println("Bike Color= "+color + " wheels= " + wheels); } public void setColor(String color) { this.color = color; } public void setwheels(int wheels) { this.wheels = wheels; } }
Step 2: Second we create a class Honda which extends the above class Bike. Here Honda class uses HondaEngine class object start() method via composition. Now we can say that Honda class HAS-A HondaEngine:
class Honda extends Bike { //inherits all properties of bike class public void setStart() { HondaEngine e = new HondaEngine(); e.start(); } }
Step 3: Third we create a class HondaEngine through which we uses this class object in above class Honda:
class HondaEngine { public void start() { System.out.println("Engine has been started."); } public void stop() { System.out.println("Engine has been stopped."); } }
Step 4: Fourth we create a class CompositionDemo in which we make an object of Honda class and initialized it:
class CompositionDemo { public static void main(String[] args) { Honda h = new Honda(); h.setColor("Black"); h.setwheels(2); h.bikeFeatures(); h.setStart(); } }
Output:
Bike color= Black wheels= 2 Engine has been started
Premium Project Source Code:
Leave a Reply