Thursday, July 23, 2015

Favour Composition over Inheritance

There are 2 ways in which a class can inherit properties from another class in JAVA.

Inheritance (is-a) and Composition (has-a).


1) is-a takes place when we use extends keyword in JAVA.

public class Dog extends Animal

Here Dog inherits the properties of Animal. This can only be done at comile time and once the assignment is done cannot be changed at runtime.



2) has-a takes place when we use reference of one class in another class.

public class Dog
{
   Animal animalObj;
  
   Dog (Animal animalObj)
   {
       this.animalObj = animalObj; 
   }
 }

Here Dog gets the properties of Animal and the assignment can be changed at runtime as well.

This feature is famously used as Dependency Injection in Springs framework.



Hence Composotion is a better option than Inheritance to inherit properties from another class.
 

2 comments:

  1. this not favor comp. over inharitance

    ReplyDelete
    Replies
    1. Have you worked on springs, dependency injection is built upon composition....Wherein you can inject objects at runtime.

      Delete

Home