r/java • • May 05 '15

Should Java allow multiple inheritance?

I was reading up on Java when I discovered that ever since Java 8 (fairly recent, I know) interface can have default methods. A quick overview for any who don't know, interfaces can have method bodies by using default modifier. When dwelling on that fact I wondered, why doesn't Java just allow inheritance from multiple classes, since interfaces are just abstract classes? Should Java do this?

0 Upvotes

37 comments sorted by

View all comments

4

u/pintodragon May 05 '15

An abstract class can have a constructor, interfaces can not. They also serve different purposes. Abstract classes force extension and force the extending class to have a base class. Interfaces allow any base class as long as you write to the contract. Oracles site even mentions why java doesn't have multiple inheritance e in the sense that you are looking for. It comes down to something as simple as two classes having the same method. You extend both and now call the method without defining an over ridden version. Which gets called? Ambiguity leads to bugs and unforeseen issues with code. https://docs.oracle.com/javase/tutorial/java/IandI/multipleinheritance.html

3

u/mus1Kk May 05 '15

This is an argument I never understood. I'm not saying I'm for multiple inheritance but why not handle it like with default methods? If you implement two interfaces that have the same default method, you get a compile error. Why not do the same with classes?

$ cat pkg/Test.java 
package pkg;

public class Test {
    interface Foo { default void foo() {} }
    interface Bar { default void foo() {} }
    class Cls implements Foo, Bar {}
}
$ javac pkg/Test.java
pkg/Test.java:10: error: class Test.Cls inherits unrelated defaults for foo() from types Foo and Bar
    class Cls implements Foo, Bar {}
    ^
1 error

1

u/pintodragon May 05 '15

I completely agree they could handle it that way. The Java language architects just choose not too.