INHERITANCE VS COMPOSITION

The Confusion because more is Known

Today I was caught in a crossfire in an argument about inheritance and composition. In OOPs, world I am relatively new so I learned something new today. As a child, when I used to play video games (Tekken 3) I try to use every action I know which caused me to bite the dust in 4 in 5 games. Same is happening here, more I know the OOPs, more I use it wrongly.

What is a composition?


class A {

  protected $name="A";

  public function getName(){
    return $this->name;
  }
}
//Reusing the codes by creating an object.
class B {
  public function doSomeAction(){
    $a = new A();
    $a->getName();
  }
}


What is an inheritance?


class A {

  protected $name="A";

  public function getName(){
    return $this->name;
  }
}
//Reusing the codes by creating an object.
class B extends A{
  public function doSomeAction(){
    $this->getName();
  }
}

Key Question!

If you ask yourself, if class B has one or many class A then it is composition If class B is class A, then it is inheritance (is_a) If class A is similar to class B then create a new class C and A and B must extend C

Examples

  • Order and Product – Order has one or more Products and thus it is a composition
  • Customer and Admin – Admin is a Customer with a special role – It is inheritance
  • OrderTag and ProductTag – Tagging functionality is same but types are different (STI) – Create a third class and inherit in both.

Tell your network!

0 Comments

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>