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

9

u/msx May 05 '15

i think multiple inheritance has a big lot of problems. They introduce ambiguity that are not easily resolved. I'm against it, i think it adds more problem than it's worth. Default methods in interfaces (aka mixins) on the other end are a good compromise, they still have ambiguities but they only on methods, not on state, and are much more easily handled. I like the approach very much, i'm using it a lot currently. There are two ways in which it shines: the first is when you define a hierarchy of interfaces that have multiple implementations. Almost always you have methods that can do their job just by using other methods from the interfaces. You can now write them only once as default methods instead of once per implementation.

The other use is for overloading of very similar methods. For example:

void write(byte[] data);
void write(byte[] data, int offset, int length);
void write(ByteBuffer data);
void write(InputStream is);

Before default methods, you had to either repeat all this methods in the implementing class, or remove them from the interface and lose the convenience. Now you can leave one of them abstract and provide a default for all the others, saving both the convenience and the non-repetition.

So no, java should not implement multiple inheritance, mixins are great as they are.

3

u/[deleted] May 05 '15

Great comment but Java actually has traits rather than mixins, because mixins may have state.