Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How interfaces achieve multiple inheritance

Tags:

c#

oop

interface

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.

like image 754
funsukvangdu Avatar asked Sep 21 '11 10:09

funsukvangdu


Video Answer


1 Answers

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);
}
like image 67
king_nak Avatar answered Sep 30 '22 16:09

king_nak