Java Inheritance and Composition

Inheritance and composition are the two common methods to reuse code in Java. Inheritance is also known as “IS-A Relationship”, composition is known as “HAS-A Relationship”. Composition is preferred over inheritance.

//Inheritance (IS-A Relationship)
public class Foo extends Bar
public class Foo {
  //Composition (HAS-A Relationship)
  Bar bar;

Some advantages of composition are:

  • If you use inheritance to reuse code, you can only extend from one class (There is no multiple inheritance in Java). Composition allows to to use more than one class.
  • Inheritance makes the subclass dependent on parent class. This creates tight coupling between classes.
  • Runtime Binding (Dynamic Binding) is used in composition, Compile Time Binding (Static Binding) is used in inheritance. This makes composition more flexible.
  • Dependency Injection in the main mechanism used in unit testing. If a class needs other classes for its operation, it takes these classes from outside. Composition is used for dependency injection.
  • Composition is also favored over inheritance in most of the design patterns due to its flexibility.

You can also use inheritance when needed. Liskov Substitution Principle can used to decide whether inheritance should be used or not. This principle briefly states that if Foo class is derived from Bar class, Bar may be replaced with Foo without any loss of program functionality (i.e. Derived classes must be substitutable for their base classes).

Related Subjects
Composition Over Inheritance
Loose Coupling
Dependency Injection
Unit Testing
Law of Demeter

SHARE