Are defaults in JDK 8 a form of multiple inheritan

2019-01-07 08:11发布

A new feature coming in JDK 8 allows you to add to an existing interface while preserving binary compatibility.

The syntax is like

public interface SomeInterface() {
  void existingInterface();
  void newInterface() default SomeClass.defaultImplementation;
}

This way for all existing implementations of SomeInterface when they upgrade to this new version they don't all suddenly have compiles errors around newInterface().

While this is neat, what happens when you are implementing two interfaces which both have added a new defaulted method which you did not implement? Let me explain with an example.

public interface Attendance {
   boolean present() default DefaultAttendance.present;
}

public interface Timeline {
   boolean present() default DefaultTimeline.present;
}

public class TimeTravelingStudent implements Attendance, Timeline {

}

// which code gets called?
new TimeTravelingStudent().present();

Has this been defined as part of JDK 8 yet?

I found the Java gods talking about something similar here http://cs.oswego.edu/pipermail/lambda-lib/2011-February/000068.html, but its part of private mailing list and I cannot ask them directly.

See this for more details on how defaults are going to be used in JDK 8 and extending the Collection interface to support lambdas: https://oracleus.wingateweb.com/published/oracleus2011/sessions/25066/25066_Cho223662.pdf

9条回答
劫难
2楼-- · 2019-01-07 08:39

There are two scenarios:

1) First, that was mentioned, where there is no most specific interface

public interface A {
   default void doStuff(){ /* implementation */ }
}

public interface B {
   default void doStuff() { /* implementation */ } 
}

public class C implements A, B {
// option 1: own implementation
// OR
// option 2: use new syntax to call specific interface or face compilation error
  void doStuff(){
      B.super.doStuff();
  }
}

2) Second, when there IS a more specific interface:

   public interface A {
       default void doStuff() { /* implementation */ } 
    }

    public interface B extends A {
       default void doStuff() { /* implementation */ } 
    }

    public class C implements A, B {
    // will use method from B, as it is "closer" to C
    }
查看更多
Ridiculous、
3楼-- · 2019-01-07 08:41

If anyone's still looking for an answer, in case a class implements two interfaces with the same default method then the class needs to resolve the disambiguity by providing an implementation of its own. Look at this tutorial for more details on how inheritance in default methods work.

查看更多
Anthone
4楼-- · 2019-01-07 08:44

As far as I see it, it is no multiple inheritance because they are stateless. So virtual extension methods don't support full object or class functionality.

查看更多
登录 后发表回答