Thursday 23 August 2012

Difference between Inheritance and Composition

They are absolutely different. Inheritance is an "is-a" & Composition is a "has-a" relationship.

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 : 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.

No comments:

Post a Comment

Custome Service Class to connect wcf service

  using  System; using  System.ServiceModel; namespace Custom.Service.Client {      // Borrowed from: http://old.iserviceoriented.com/blog/p...