7

In many books it is written that interfaces are a replacement of multiple inheritance, but I don't find any similarity between both of them.

Inheritance is mostly important for re-usability of code and functionality and multiple inheritance was helping to re-use code from more than one class, but in interface I didn't find any such feature except that a class can inherit from more than one interface.

Interface is just declaration of functions/methods and it didn't contain any implementation part by itself, so class which are inheriting this interface should have to write their own implementation code.

So I don't feel any re-usability of code in case of interface.

Is any document or link which will clear my doubts with you answer please share.

6
  • 2
    "Inheritance is mostly important for re-usability of code" - No, that is a minor aspect. Commented Sep 21, 2011 at 11:33
  • 1
    What are the other aspects of Inheritance Commented Sep 21, 2011 at 12:03
  • 2
    You want to use classes and inheritance to build a logical and consisten model of your application domain. Re-use follows where it is needed. Commented Sep 21, 2011 at 12:35
  • 4
    Multiple implementation inheritance is a bug factory, therefore explicitly not supported in .NET. en.wikipedia.org/wiki/Diamond_problem Commented Sep 21, 2011 at 13:00
  • Can you please explore in details how inheritance is used to build logical and consistent model of application domain. Commented Sep 21, 2011 at 16:10

6 Answers 6

3

Regarding reusability of code, you are right. In that respect, multiple interfaces are no replacement of multiple inheritance.

However, there's another aspect of inheritance: it establishes an is-a relasionship between the base- and sub-class. So a class inheriting multiple super-classes can act as any of them. In this respect, interfaces serve as a valid replacement, e.g. a method accepting an interface will also accept any class implementing that interface, in the same way as a method will accept any class derived from the excpected class. But as you stated, each class has to implement the interface methods by their own.

Example:

public interface Foo {
    int doFoo();
}

public interface Bar {
    long doBar();
}

public class Baz {
    String doBaz() {
        return "This is baz";
    }
}

public class FooBar extends Baz implements Foo, Bar {
    public long doBar() {
        return 123;
    }
    public int doFoo() {
        return 456;
    }
}

// Accepts interface Bar implementing objects
public void doSomething(Bar b) {
    System.out.println(b.doBar() * 10);
}

// Accepts interface Foo implementing objects
public void doSomethingOther(Foo f) {
    System.out.println(f.doFoo() / 10);
}

// Accepts objects of class Baz and subclasses
public void doMore(Baz b) {
    System.out.println(b.doBaz());
}

void bla() {
    FooBar fb = new FooBar();

    // FooBar can act as Foo, Bar, and Baz
    doSomething(fb);
    doSomethingOther(fb);
    doMore(fb);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Can U please explore point "a method accepting an interface ...." in detail with some sample code.
2

You are right.

People mean that a type in C# can implement multiple interfaces. This is not the same as classic inheritance.

It does allow you to use one class in many different contexts, and any class inheriting from such a class will of course be able to use the base class implementation for reuse.

Comments

0

See This Example.

 /*interface 1 with two methods*/
    interface IA1
    {
        void Foo1();
        void Foo2();
    }   
   /*Interface two with two methods */
    interface IA2
    {
        void Foo1();
        void Foo3();
    }   



 /*class implemeting two interfaces now. Here class cannot inherit two classes but can inherit two interfcaes.*/
  /* Case1 */
    class CA : IA1, IA2  
    { 
        void IA1.Foo1()//Explicitly Implemented
        {
            Console.WriteLine("In IA1.Foo1");
        }
        void IA2.Foo1() //Explicitly Implemented
        {
            Console.WriteLine("In IA2.Foo1");
        }
        public void Foo2()  //Implicitly Implemented
        {
            Console.WriteLine("In IA1.Foo2");
        }
        public void Foo3()  //Implicitly Implemented
        {
            Console.WriteLine("In IA2.Foo3");
        }
    }


 /* Case2*/
    class CA : IA1, IA2   {
        public void Foo1() //Implicitly Implemented
        {
            Console.WriteLine("In Foo1");
        }
        public void Foo2()  //Implicitly Implemented
        {
            Console.WriteLine("In Foo2");
        }
        public void Foo3()  //Implicitly Implemented
        {
            Console.WriteLine("In Foo3");
        }
    }   

Using the concept of interface a class can inherit one or more interfaces. And can implement own functionality for the inherited interfaces.

Comments

0
 Inheritance is mostly important for re-usability of code and functionality 
 and multiple inheritance was helping to re-use code from more than one class, 
 but in Interface I didn't find any such feature except that a class can inherit 
 from more than one interface.

It is true that interfaces promote code reusability (especially in conjuction with polymorphism, inheritance can do wonders!). I could name another situation where interfaces could be beneficial: callbacks.

Since we have delegates in C#, I doubt if there's any C# developer who will use interfaces as a medium for callbacks (probably a C# developer using C# 1.0). But for Java developers, how they are going to implement callbacks without delegates? The answer: interfaces.

Callbacks Using Delegates

public delegate int Transformer (int x);

class Util
{
    public static void Transform (int[] values, Transformer t)
    {
        for (int i = 0; i < values.Length; i++)
            values[i] = t (values[i]);
    }
}

class Test
{
    static void Main()
    {
        int[] values = { 1, 2, 3 };
        Util.Transform (values, Square);
        foreach (int i in values)
            Console.Write (i + " "); 
    }

    static int Square (int x) { return x * x; }
}

Callbacks Using Interfaces

public interface ITransformer
{
    int Transform (int x);
}

public class Util
{
    public static void TransformAll (int[] values, ITransformer t)
    {
        for (int i = 0; i < values.Length; i++)
            values[i] = t.Transform (values[i]);
    }
}

class Squarer : ITransformer
{
    public int Transform (int x) { return x * x; }
}

static void Main()
{
    int[] values = { 1, 2, 3 };
    Util.TransformAll (values, new Squarer());
    foreach (int i in values)
         Console.WriteLine (i);
}

For further reading about Callbacks, refer to C# Callbacks with Interfaces and Delegates and Implement callback routines in Java.

NOTE: The sample code in this post is taken from the book C# 4.0 in a Nutshell (which is also a good C# reference).

Well-known developers warned us about the perils of inheritance:
Why extends is evil by Allen Holub
OOP The Good Parts: Message Passing, Duck Typing, Object Composition, and not Inheritance by Nick Fitzgerald
Seven deadly sins of programming - Sin #2: Overuse of Inheritance by Eric Gunnerson

1 Comment

Interfaces can sometimes be an excellent mechanism for callbacks. For example, the "acquire" routine for a wrapped mutex (which could be a Monitor lock, a Semaphore, a SemaphoreSlim, or a BobsSuperDeluxeMutex) could return a MethodInvoker or an IDisposable to provide for its release, but the normal practice would be IDisposable.
0

Inheritance combines two somewhat orthogonal concepts:

  1. The derived class can implicitly use the parent class' methods and fields to handle those parts of its behavior which match those of the parent class.
  2. Objects of the derived class can be used just about anywhere objects of the parent class can be used.

Allowing a class to implicitly use methods and fields from more than one parent class can result in some tricky issues, e.g. if class X provides an abstract method foo(), classes Y and Z both inherit X and provide different implementations of foo(), and class Q tries to inherit Y and Z. If an object o of class Q is passed to a method expecting an X (legitimate, since objects of a derived class may be used where objects of the parent class can be used), what should happen if that method tries calling o.foo()?

Such issues generally do not exist with interfaces. If interfaces IY and IZ inherit from interface IX which contains foo(), and interface IQ inherits both of those, a class implementing IQ must provide an implementation for IQ.foo(), which will also be used for IY.foo(), IZ.foo(), and IX.foo(). It's possible to create ambiguous situations, but those result in compile-time squawks.

Comments

-1

Actually, I have no good answer other than C#, Java have no Multiple Inheriance and it SHOULD have. The whole point that interfaces should be able to replace the need for Multiple Inheritance is like the big lie that when repeated enough times becomes true.

The argument is that Multiple Inheritance causes all these problems, yet I keep hearing those arguments from C#, Java developers who have never used C++. I also don't EVER remember C++ programmers saying "Gee, I love C++, but if they would only get rid of Multiple Inheritance, it would become a great language". People used it when it was practical and didn't when it wasn't.

Your problem is a classic case of where Multiple Inheritance would be appropriate. Any suggestion to refactor the code is really telling you how to work around the PROBLEM that C#, Java have no Multiple Inheritance.

Also all the discussion that "oh, delegation is better, la-di-dah" is confusing religion with design. There is no right way. Things are either more useful or less useful and that is all.

In your case Multiple Inheritance would be more useful and a more elegant solution.

As far as refactoring your code into a less useful form to satisfy all the religious people who have never used Multiple Inheritance and believe "Multiple Inheritance is bad", I guess you will have to downgrade your code because I don't see C#, Java "improving" in that way any time soon. There are too many people repeating the religious mantra to the point of stupidity that I can't see it ever being added to the language.

...but as you can see from the solutions provided above, most people think that such a solution would be WAY TOO COMPLEX AND CONFUSING!

I would prefer to venture into the "x extends a,b" territory myself, even if it is a very frightening solution that might overwhelm the abilities of most C#, Java programmers.

What is even more amazing about the solutions suggested above is that everyone here who suggested that you refactor your code into "delegation" because Multiple Inheritance is bad, would, if they were confronted with the very same problem, would solve the problem by simply doing: "x extends a,b" and be done with it, and all their religious arguments about "delegation vs inheritance" would disappear. The whole debate is stupid, and it only being advanced by clueless programmers who only demonstrate how well they can recite out of a book and how little they can think for themselves.

You are 100% correct that Multiple Inheritance would help, and no, you are doing anything wrong in your code if you think C#, Java should have it.

2 Comments

No @MattDavey! its a reallity.
it is your opinion, nothing more.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.