3

Possible Duplicate:
Why there is no multiple inheritance in Java, but implementing multiple interfaces is allowed

Every answer I have seen so far regarding "Why Java has no multiple inheritance" has only one answer in more specific or detailed way that is "To reduce complexity" but no one defined how it reduces complexity, If we use interface instead of class what difference it makes.Isn't it one and a same thing? what is the difference if we implement an interface and not extend our class?Some one answered with Diamond problem but interfaces can also produce diamond problems.

Community
  • 1
  • 1
Just_another_developer
  • 5,737
  • 12
  • 50
  • 83

2 Answers2

6

The difference between multiple inheritance among interfaces vs. classes is when you must inherit implementation. When you inherit method interface through multiple paths, you can say that the implementing class must implement the inherited method. When you inherit from multiple classes, you must decide which of the several implementations to choose. This increases the complexity of the language very significantly, as you can see by examining the way multiple inheritance is implemented in C++.

Here is an illustration:

public class Base {
    public void foo() {System.out.println("base");}
}
public class A extends Base {
    public void foo() {System.out.println("a");}
}
public class B extends Base {
    public void foo() {System.out.println("b");}
}
public class AB extends A, B /* imagine that it's a possibility */{
}

What is going to happen when you do this?

AB ab = new AB();
ab.foo();

With inheritance of interfaces, AB would have to implement foo; with inheritance of implementation, the language would need to decide, or provide you a way to specify it yourself. One way or the other, the complexity is going to grow.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

Interfaces don't come with code: only a set of methods that must be implemented.

Classes come with code. When you have a diamond problem with classes, you end up with two implementations for the same function, that may reference the same variables.

With interfaces, there's only ever one implementation, although the interface can come from many places.

Max
  • 10,701
  • 2
  • 24
  • 48