Inheritance != Interface
Why Interfaces are not Multiple Inheritances
“a class implements an interface”
An interface’s main goal is to ensure that all classes implementing the interface are adhering to a contract.
They look like a class, however, interfaces only contain the declaration of the members with no implementation. We know what we want our subclasses to be able to do, but we are not concerned with how that will be done. Usually, this is because “how it is done” can vary.
Take a look at the example interface above. It is a logger interface that declares two methods, LogError and LogInfo. Now the interface doesn't care how those methods work but only that they both exist. We could create a class that logs to the console, then another that logs to a file. Both these classes could implement our logger interface and have completely different LogError and LogInfo methods. The interface simply ensures that the classes will have the methods.
“a class inherits from a base class”
I want to stress that interfaces are not inheritance.
The main reason for using inheritance is code reusability. It’s used to give subclasses the same methods as the base class, without having to re-write any code at all! The class inherits the implementation of the methods in the base class.
Interfaces are not providing code reusability since they contain no code for implementations of their methods!
Interfaces are not Multiple Inheritances
C# has a singular inheritance. This means each subclass can only inherit from one base class. This was done since multiple inheritances can be a bad practice in OOP as it can make the source more complicated.
Now even though C# does not allow for multiple inheritances, C# does allow you to implement multiple interfaces to a class. However, multiple interfaces, this is not the same as having multiple inheritances!
Interfaces guarantee that an object implements specific contracts. Multiple interfaces mean an object supports multiple contracts. This is not multiple inheritances, which means the object would inherit both the interface and the implementation.
The best way to summarize the difference between interfaces and inheritence:
- Inheritance describes an is-a relationship
- Implementing an interface describes a can-do relationship