0 votes
in JAVA by
Although inheritance is a popular OOPs concept, it is less advantageous than composition. Explain.

1 Answer

0 votes
by

Inheritance lags behind composition in the following scenarios:

Multiple-inheritance is not possible in Java. Classes can only extend from one superclass. In cases where multiple functionalities are required, for example - to read and write information into the file, the pattern of composition is preferred. The writer, as well as reader functionalities, can be made use of by considering them as the private members.

Composition assists in attaining high flexibility and prevents breaking of encapsulation.

Unit testing is possible with composition and not inheritance. When a developer wants to test a class composing a different class, then Mock Object can be created for signifying the composed class to facilitate testing. This technique is not possible with the help of inheritance as the derived class cannot be tested without the help of the superclass in inheritance.

The loosely coupled nature of composition is preferable over the tightly coupled nature of inheritance. Let’s take an example:

package comparison;

public class Top {

public int start() {

  return 0;

}

}

class Bottom extends Top {

  public int stop() {

  return 0;

  }

}

In the above example, inheritance is followed. Now, some modifications are done to the Top class like this:

public class Top {

  public int start() {

  return 0;

  }

  public void stop() {

  }

}

If the new implementation of the Top class is followed, a compile-time error is bound to occur in the Bottom class. Incompatible return type is there for the Top.stop() function. Changes have to be made to either the Top or the Bottom class to ensure compatibility. However, the composition technique can be utilized to solve the given problem:

class Bottom {

  Top par = new Top();

  public int stop() {

  par.start();

  par.stop();

  return 0;

  }

 }

...