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:
Object effectively has two identities: a
Tank
is both aVehicle
and aWeapon
. You can use an instance ofTank
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).Simple responsibilities: an instance of
Tank
object in a game is alsoRunnable
to let you execute it in a thread and anActionListener
to 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
instanceof
to discover object capabilities or wishes.Serializable
andCloneable
are examples of this.
What you are looking for are trait (like in Scala), unfortunately unavailable in Java.
Interfaces are collection of final static fields and abstract methods (Newly Java 8 added support of having static methods in an interface).
Interfaces are made in situations when we know that some task must be done, but how it should be done can vary. In other words we can say we implement interfaces so that our class starts behaving in a particular way.
Let me explain with an example, we all know what animals are. Like Lion is an animal, monkey is an animal, elephant is an animal, cow is an animal and so on. Now we know all animals do eat something and sleep. But the way each animal can eat something or sleep may differ. Like Lion eats by hunting other animals where as cow eats grass. But both eat. So we can have some pseudo code like this,
interface Animal {
public void eat();
public void sleep();
}
class Lion implements Animal {
public void eat() {
// Lion's way to eat
}
public void sleep(){
// Lion's way to sleep
}
}
class Monkey implements Animal {
public void eat() {
// Monkey's way to eat
}
public void sleep() {
// Monkey's way to sleep
}
}
As per the pseudo code mentioned above, anything that is capable of eating or sleeping will be called an animal or we can say it is must for all animals to eat and sleep but the way to eat and sleep depends on the animal.
In case of interfaces we inherit only the behaviour, not the actual code as in case of classes' inheritance.
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.
Implementing interfaces is other kind of inheritance. It is not similar to the inheritance of classes as in that inheritance child class gets the real code to reuse from the base class.
Q2. If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritance ?
It is said because one class can implement more than one interfaces. But we need to understand that this inheritance is different than classes' inheritance.
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.
Implementing an interface puts compulsion on the class that it must override its all abstract methods.
Read more in my book here and here
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.
Unfortunately, in colloquial usage, the word inheritance
is still frequently used when a class implements an interface, although interface implementation
would be a preferable term - IMO, the term inheritance
should strictly be used with inheritance of a concrete or abstract class. In languages like C++ and C#, the same syntax (i.e. Subclass : Superclass
and Class : Interface
) is used for both class inheritance and interface implementation, which may have contributed to the spread of the misuse of the word inheritance
with interfaces. Java has different syntax for extend
ing a class as opposed to implement
ing an interface, which is a good thing.
Q2 If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritance ?
You can achieve the 'effect' of multiple inheritance through composition - by implementing multiple interfaces on a class, and then providing implementations for all methods, properties and events required of all the interfaces on the class. One common technique of doing this with concrete classes is by doing 'has-a' (composition) relationships with classes which implement the external interfaces by 'wiring up' the implementation to each of the internal class implementations. (Languages such as C++ do support multiple concrete inheritance directly, but which creates other potential issues like the diamond problem).
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 allow existing classes (e.g. frameworks) to interact with your new classes without having ever 'seen' them before, because of the ability to communicate through a known interface. Think of an interface as a contract. By implementing this interface on a class, you are contractually bound to meet the obligations required of it, and once this contract is implemented, then your class should be able to be used interchangeably with any other code which consumes the interface.
Real World Example
A 'real world' example would be the legislation and convention (interface) surrounding an electrical wall socket in a particular country. Each electrical appliance plugged into the socket needs to meet the specifications (contract) that the authorities have defined for the socket, e.g. the positioning of the line, neutral and earth wires, the position and colouring of the on / off switch, and the conformance the the electrical voltage, frequency and maximum current that will be supplied through the interface
when it is switched on.
The benefit of decoupling the interface (i.e. a standard wall socket) rather than just soldering wires together is that you can plug (and unplug) a fan, a kettle, a double-adapter, or some new appliance to be invented next year into it, even though this appliance didn't exist when the interface was designed. Why? Because it will conform to the requirements of the interface.
Why use interfaces?
Interfaces are great for loose coupling of classes, and are one of the mainstay's of Uncle Bob's SOLID paradigm, especially the Dependency Inversion Principle
and Interface Segregation Principles
.
Simply put, by ensuring that dependencies between classes are coupled only on interfaces (abstractions), and not on other concrete classes, it allows the dependency to be substituted with any other class implementation which meets the requirements of the interface.
In testing, stubs and mocks of dependencies can be used to unit test each class, and the interaction the class has with the dependency can be 'spyed' upon.