g.pickardou
g.pickardou

Reputation: 35822

Interface with default methods vs abstract class, and what's the motivation?

Context

I've recently came across this C# proposal default interface methods I've read both the specification and more importantly the motivation. Possibly I missed something, but the motivation is a bit stinks me.

The only practical difference between interface and a fully abstract class was that a future class can implement (so be [IS A]) multiple interfaces, but can inherit (so be [IS A]) from only one abstract class, (and all the consequences)

What is not clear for me what is the exact difference between abstract classes and interfaces with default methods now, except that we can bring multiple (implementation) inheritance into the picture with default methods, which is not possible with abstract classes. (I do not want open the question/discussion is it good or bad, this is not the topic here)

However the motivation talks about completely different, three points:

Question

My question is what is the real difference (or motivation), or what am I missing?

Upvotes: 15

Views: 2944

Answers (2)

nandhu
nandhu

Reputation: 21

After introducing Default Method, it seems that interfaces and abstract classes are the same. However, they are still a different concept in Java 8.

The abstract class can define constructors. They are more structured and can have a state associated with them. While in contrast, default method can be implemented only in the terms of invoking other interface methods, with no reference to a particular implementation's state. Hence, both are used for different purposes and choosing between two really depends on the scenario context.

Upvotes: 2

fharreau
fharreau

Reputation: 2327

They add this feature in Java 8. So you can add the Java tag and ask to Java developers what they can do with it. It also exists on Haskell and Scala apparently.

Multi-Inheritance

What come to my mind first is Multi-Inheritance. As a class can implement multiple interfaces, you can for example to solve the diamond problem.

In Java this is how they do:

public interface InterfaceA {
    public default void foo() {
        System.out.println("A -> foo()");
    }
}

public interface InterfaceB {
    public default void foo() {
        System.out.println("B -> foo()");
    }
}

private class Test implements InterfaceA, InterfaceB {
    // Compilation error : "class Test inherits unrelated defaults for foo() from types InterfaceA and InterfaceB"
}

So you have to either implement the methods (which override the default implementations) or call one of the super:

public class Test implements InterfaceA, InterfaceB {
     public void foo() {
        InterfaceB.super.foo();
    }
}

Upvotes: 2

Related Questions