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
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
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:
Object effectively has two identities: a
Tankis both a
Weapon. You can use an instance of
Tankwhere 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).
Simple responsibilities: an instance of
Tankobject in a game is also
Runnableto let you execute it in a thread and an
ActionListenerto respond to mouse events.
Callback interfaces: if object implements given callback interface, it is being notified about its life-cycle or other events.
Marker interfaces: not adding any methods, but easily accessible via
instanceofto discover object capabilities or wishes.
Cloneableare examples of this.
What you are looking for are trait (like in Scala), unfortunately unavailable in Java.