user252521
user252521

Reputation: 71

Difference between inheritance and composition

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

Upvotes: 1

Views: 4962

Answers (4)

Zahra.HY
Zahra.HY

Reputation: 1692

In simple words, Composition means HAS-A relationship but Inheritance is an IS-A relationship.

For example, a chicken is a bird and has a beak. So the following code snippet shows how it works:

/*
* Parent class for Chicken.
*/
class Bird {
    ...
    //code
}  

class Beak {
    ...
    //code
} 

/* 
* As Chicken is a bird so it extends the Bird class. 
*/
class Chicken extends Bird { 

      private Beak beak; // Chicken has a beak so, Chicken class has an instance of Beak class. 
}

Upvotes: 0

Steve
Steve

Reputation: 11

It also means that the encapsulation of the parent is not broken. Subclassing exposes the data of the parent class to the child class, thus breaking the encapsulation. Composition allows the object encapsulation to persist and both objects can continue to be managed separately, so that changing the data of one class does not affect the other class data.

Upvotes: 1

ChickSentMeHighE
ChickSentMeHighE

Reputation: 1706

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.

Upvotes: 8

JSBձոգչ
JSBձոգչ

Reputation: 41378

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.

Upvotes: 1

Related Questions