Why to use Interfaces, Multiple Inheritance vs Interfaces, Benefits of Interfaces?

Q1. As interfaces are having only abstract methods (no code) so how can we say that if we are implementing any interface then it is inheritance ? We are not using its code.

We can’t. Interfaces aren’t used to achieve multiple inheritance. They replace it with safer, although slightly less powerful construct. Note the keyword implements rather than extends.

Q2. If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritance ?

They are not. With interfaces a single class can have several “views“, different APIs or capabilities. E.g. A class can be Runnable and Callable at the same time, while both methods are effectively doing the same thing.

Q3. Anyhow what is the benefit of using Interfaces ? They are not having any code. We need to write code again and again in all classes we implement it.

Interfaces are kind-of multiple inheritance with no problems that the latter introduces (like the Diamond problem).

There are few use-cases for interfaces:

  1. Object effectively has two identities: a Tank is both a Vehicle and a Weapon. You can use an instance of Tank where either the former or the latter is expected (polymorphism). This is rarely a case in real-life and is actually a valid example where multiple inheritance would be better (or traits).

  2. Simple responsibilities: an instance of Tank object in a game is also Runnable to let you execute it in a thread and an ActionListener to respond to mouse events.

  3. Callback interfaces: if object implements given callback interface, it is being notified about its life-cycle or other events.

  4. Marker interfaces: not adding any methods, but easily accessible via instanceof to discover object capabilities or wishes. Serializable and Cloneable are examples of this.

What you are looking for are trait (like in Scala), unfortunately unavailable in Java.

Leave a Comment