Why to Use Interfaces, Multiple Inheritance VS Interfaces, Benefits of Interfaces

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

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

Do interfaces have any purpose besides achieving polymorphism and multiple inheritance?

if an interface were inherited by only one class, it would be useless

I agree, but you can read a lot of discussion on this topic in Java Interfaces Methodology: Should every class implement an interface?

when an interface is inherited by multiple classes, it makes no difference unless it is used for polymorphism

I agree, it would be silly to implement an interface and then bypass it by invoking its methods directly on the concrete class. The purpose of implementing an interface is to have its abstract methods called, which is polymorphism in action. Since polymorphism is the primary tool of Object Oriented Programming, you could take this statement a step further and say that OOP makes no difference unless it is used for polymorphism.

the only thing that makes implementation different from extension is multiple inheritances

No, the primary difference between these Java constructs is that interface implementation facilitates stateless inheritance whereas class extension facilitates stateful inheritance. Java happens to support multiple stateless inheritance and single stateful inheritance. This dichotomy may be considered a mistake.

Do interfaces have any purpose besides achieving polymorphism and multiple inheritance?

In practice, yes. You can find interfaces used for other purposes such as constant interfaces or marker interfaces. Whether these practices are advisable has been debated.

C# What is the advantage of using interfaces for simulating multiple inheritance?

Yes you're right. The code will still compile after you remove the interfaces. So why add them?

Well, your IAddition and ISubtraction examples aren't really good to make my point here. Since the best way to learn programming is to look at how other people code, I'll use the System.IComparable<T> interface as an example. It is an interface provided by the .NET framework.

The reason why we use interfaces is to achieve polymorphism. Interfaces are like protocols which classes must conform to. If a class implements an interface, it is guaranteed that the class can do the things that the interface specifies. This all sounds quite confusing so let's take a look at the IComparable<T> interface. To make things simpler, let's make it IComparable<int>

IComparable<int> has this method:

int CompareTo(int other);

This basically means

Everything that implements IComparable<int> has the ability to be compared with an integer. We can call its CompareTo method to decide whether it is bigger than, equal to, or less than any int.

Since everything that implemets IComparable<int> must have the method CompareTo, it is guaranteed that the object you're calling CompareTo on can be compared with an int.

So how is this useful?

The ability to be compared with something else is useful when you sort arrays. The Array.Sort method make use of the IComparable<T> interface. Here's how the Sort method works (highly simplified):

It first checks whether the array's elements can be compared by checking whether they implement IComparable<T>. If they do, compare them by calling CompareTo! Why can it be so sure that there is a method called CompareTo? Because the objects all implement IComparable<T>, which guarantees a CompareTo method! After comparing, Sort can figure out which element comes first and last.

You see how different things need to be compared differently? Integers and doubles can be compared by subtracting one from the other and checking whether the result is a positive or negative number. But strings are compared alphabetically. If there weren't a IComparable<T> interface, there would have been a different Sort method for strings, and a Sort method for int, and a Sort method for all the types that can be compared. Worse, if client code creates something that can be compared, the client code needs to write its own Sort method! Don't forget that there are a ton of other methods that make use of the ability to be compared. Do all those methods need a different version for each type?

That's why interfaces are so important. With them, only one Sort method is needed because polymorphism takes care of the rest.

Let me summarise the advantages of interfaces:

  • It provides flexibility (integers and strings can both be compared to integers and strings, but in different ways)
  • It reduces code (You don't need to write extra Sort methods!)
  • It ensures safety (If you forgot to implement a method, the compiler will tell you!)

Let's assume that IComparable<T> does not exist, and string and int and other types that can be compared as their own CompareTo method. The Sort methods can look like this

public static void Sort(int[] arr) {
// note that I'm using bubble sort here. A real sort method wouldn't use this coz it's slow.
// source: http://stackoverflow.com/questions/14768010/simple-bubble-sort-c-sharp
int temp = 0;

for (int write = 0; write < arr.Length; write++) {
for (int sort = 0; sort < arr.Length - 1; sort++) {
if (arr[sort].CompareTo(arr[sort + 1]) > 0) {
temp = arr[sort + 1];
arr[sort + 1] = arr[sort];
arr[sort] = temp;
}
}
}

}

public static void Sort(string[] arr) {
string temp = 0;

for (int write = 0; write < arr.Length; write++) {
for (int sort = 0; sort < arr.Length - 1; sort++) {
if (arr[sort].CompareTo(arr[sort + 1]) > 0) {
temp = arr[sort + 1];
arr[sort + 1] = arr[sort];
arr[sort] = temp;
}
}
}

}

You could argue that one Sort method that takes an object[] checks the type of each element could also work. Yes, but that suffers from the same problem as multiple Sort methods. You still need to add another sort method or another check if a new comparable class is created.

The problem all end if you have a IComparable<T> interface!

public static void Sort<T>(T[] arr) where T : IComparable<T> {
T temp;

for (int write = 0; write < arr.Length; write++) {
for (int sort = 0; sort < arr.Length - 1; sort++) {
if (arr[sort].CompareTo(arr[sort + 1]) > 0) {
temp = arr[sort + 1];
arr[sort + 1] = arr[sort];
arr[sort] = temp;
}
}
}
}

Since the type constraint says that T must implement IComparable<T>, CompareTo can be called on every object in the array with no problems!

Now all you need to do if you wish to add another comparable class is to implement the interface. Whereas if the interface didn't exist, you have to write a CompareTo method and a Sort method!

When should I choose inheritance over an interface when designing C# class libraries?

Generally, the rule goes something like this:

  • Inheritance describes an is-a relationship.
  • Implementing an interface describes a can-do relationship.

To put this in somewhat more concrete terms, let's look at an example. The System.Drawing.Bitmap class is-an image (and as such, it inherits from the Image class), but it also can-do disposing, so it implements the IDisposable interface. It also can-do serialization, so it implements from the ISerializable interface.

But more practically, interfaces are often used to simulate multiple inheritance in C#. If your Processor class needs to inherit from something like System.ComponentModel.Component, then you have little choice but to implement an IProcessor interface.

The fact is that both interfaces and abstract base class provide a contract specifying what a particular class can do. It's a common myth that interfaces are necessary to declare this contract, but that's not correct. The biggest advantage to my mind is that abstract base classes allow you provide default functionality for the subclasses. But if there is no default functionality that makes sense, there's nothing keeping you from marking the method itself as abstract, requiring that derived classes implement it themselves, just like if they were to implement an interface.

For answers to questions like this, I often turn to the .NET Framework Design Guidelines, which have this to say about choosing between classes and interfaces:

In general, classes are the preferred construct for exposing abstractions.

The main drawback of interfaces is that they are much less flexible than classes when it comes to allowing for the evolution of APIs. Once you ship an interface, the set of its members is fixed forever. Any additions to the interface would break existing types implementing the interface.

A class offers much more flexibility. You can add members to classes that you have already shipped. As long as the method is not abstract (i.e., as long as you provide a default implementation of the method), any existing derived classes continue to function unchanged.

[ . . . ]

One of the most common arguments in favor of interfaces is that they allow separating contract from the implementation. However, the argument incorrectly assumes that you cannot separate contracts from implementation using classes. Abstract classes residing in a separate assembly from their concrete implementations are a great way to achieve such separation.

Their general recommendations are as follows:

  • Do favor defining classes over interfaces.
  • Do use abstract classes instead of interfaces to decouple the contract from implementations. Abstract classes, if defined correctly, allow for the same degree of decoupling between contract and implementation.
  • Do define an interface if you need to provide a polymorphic hierarchy of value types.
  • Consider defining interfaces to achieve a similar effect to that of multiple inheritance.

Chris Anderson expresses particular agreement with this last tenet, arguing that:

Abstract types do version much better, and allow for future extensibility, but they also burn your one and only base type. Interfaces are appropriate when you are really defining a contract between two objects that is invariant over time. Abstract base types are better for defining a common base for a family of types.

Advantages of multiple inheritance over interface

whenever you need common behaviour from two distinct classes. Interface just carry "method signatures", whereas classes carry actual behaviour. Multiple inheritance greatly helps to reduce boilerplate code.

I am no longer a C++ programmer (30kg ago I was). I went from C++ to Java to Scala... where traits were introduced. They shine a new light on multiple inheritance (even to people who though that it was an invention from the devil).

Benefits of implement interface over inherit classes

One key advantage of interfaces in a single inheritance language is that interfaces can be implemented on classes that do not share a common root.

Another point is that interfaces allow what is known as interface inheritance rather than implementation inheritance. This can sometimes be very useful but proponents of true multiple inheritance regard the lack of multiple implementation inheritance a crucial weakness of C#, Java etc.

Why is multiple inheritance not the main purpose of interfaces?

In a statically typed language, or when using static typing in a language that has both dynamic and static typing (such as C#), then inheritance consists of two pieces. The interface, and the implementation. The interface is a contract that says that it will fulfill a specific set of methods or properties. The implementation is the code that actually does it. Code implements an interface.

Interfaces are used to guarantee that an object implements specific contracts. This can be a single contract, or multiple ones. This is not multiple inheritance, which inherits both the interface and the implementation.

Yes, some people try to simulate multiple inheritance with multiple interfaces, but that's not its purpose, and that simulation is very poor anyways.

Multiple interfaces says that an object supports multiple contracts. Multiple inheritance says that an object re-uses multiple implementations. Again, inheritance requires both interface and implementation. Interface implementation is just the interface.

Should I include all the interfaces in the inheritance chain?

They are identical.

This is not about explicit interface implementation, because one can implement interface explicitly using both Child1 and Child2 styles, e.g.:

public class Child2 : IGrandparent, IParent
{
void IGrandparent.DoSomething()
{
throw new NotImplementedException();
}

public void DoSomethingElse()
{
throw new NotImplementedException();
}
}

public class Child1 : IParent
{
void IGrandparent.DoSomething()
{
throw new NotImplementedException();
}

public void DoSomethingElse()
{
throw new NotImplementedException();
}
}

Note, that this shouldn't be confused with interface re-implementation within class hierarchy:

public class Child1 : IParent
{
public void DoSomething()
{
Console.WriteLine("Child1.DoSomething");
}

public void DoSomethingElse()
{
Console.WriteLine("Child1.DoSomethingElse");
}
}

public class Child2 : Child1, IGrandparent
{
// Child2 re-implements IGrandparent
// using explicit interface implementation
void IGrandparent.DoSomething()
{
Console.WriteLine("Child2.DoSomething");
}
}

I'd avoid Child2 style. It's just a visual trash. Moreover, if IGrandparent isn't your responsibility, then sometime you will get this:

interface IGrandparent : ICthulhu { ... }

Do you want to update your code this way:

public class Child2 : ICthulhu, IGrandparent, IParent { ... }

?



Related Topics



Leave a reply



Submit