Inheritance

It is the design technique in object oriented programming to implement Is-A relationship between objects. Inheritance in Java is implemented using extends keyword.

class Fruit {

}

class Apple extends Fruit {

}

Class Apple is related to class Fruit by inheritance, because Apple extends Fruit. In this example, Fruit is the superclass and Apple is the subclass. Below is the UML diagram showing the inheritance relationship between Apple and Fruit.

Inheritance relationship

Composition

It is the design technique in object oriented programming to implement Has-A relationship between objects. Composition in Java is achieved by using instance variables of other objects. Composition, simply mean using instance variables that are references to other objects. For example:

class Fruit {

}

class Apple {

  private Fruit fruit = new Fruit();
}

Class Apple is related to class Fruit by composition, because Apple has an instance variable that holds a reference to a Fruit object. The UML diagram showing the composition relationship has a darkened diamond.

composition relationship

Composition vs Inheritance

Both composition and inheritance promotes code reuse through different approaches. Composition is preferred over Inheritance. Difference between composition vs inheritance are

  • Inheritance is tightly coupled whereas composition is loosely coupled.
  • There is no access control in inheritance whereas access can be restricted in composition. We expose all the superclass methods to the other classes having access to subclass. So if a new method is introduced or there are security holes in the superclass, subclass becomes vulnerable. Since in composition we choose which methods to use, it’s more secure than inheritance.
  • Composition provides flexibility in invocation of methods that is useful with multiple subclass scenario.

Is-A Relationship

An Is-A relationship is inheritances. Classes which inherit are known as sub classes or child classes. For example, a Potato Is-A vegetable, a Bus is a vehicle, and so on. One of the properties of inheritance is that inheritance is unidirectional in nature. Like we can say that a house is a building. But not all buildings are houses. When there is an extends or implement keyword in the class declaration in Java, then the specific class is said to be following the Is-A relationship.

Has-A Relationship

Has-A relationship is composition. A Has-A relationship simply means that an instance of one class has a reference to an instance of another class or an other instance of the same class. For example, a dog Has-A tail and so on.