views:

86

answers:

2

I have extracted following difference between inheritance and composition. I wanted to know what does delay of creation of back end object mean? Please find below difference.

Composition allows you to delay the creation of back-end objects until (and unless) they are needed, as well as changing the back-end objects dynamically throughout the lifetime of the front-end object. With inheritance, you get the image of the superclass in your subclass object image as soon as the subclass is created, and it remains part of the subclass object throughout the lifetime of the subclass

+1  A: 

All it means is that the object that your class encapsulates doesn't have to be created until somebody actually calls the method that uses that object.

JSBangs
+4  A: 

In inheritance the superclass is created when the subclass is created. In Composition, the object is created when the coder wants it to.

This is inheritance, when the Child class is created the parent is created because the child inherits from parent.

class Parent {

    //Some code
}

class Child extends Parent{

    //Some code
}

This is composition, the object is not created when the child class is created, instead it is created whenever it is need.

class Parent{

    //Some code
}

class Child{

    private Parent parent = new Parent();
    //Some code
}

In this case, the Parent class is also created when the Child class is created. Below is another example of Composition without the object being created when the child class is created

class Parent{

    //Some code
}

class Child{

    private Parent parent;

    public Child()
    {
    }
    public void createParent()
    {
         parent = new Parent();
    }
}

Note how the parent is not created until a call is made to the createParent.

MikeAbyss