Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

interface - Are defaults in JDK 8 a form of multiple inheritance in Java?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The answer to the duplicate operation is:

To solve multiple inheritance issue a class implementing two interfaces providing a default implementation for the same method name and signature must provide an implementation of the method. [Full Article]

My answer to your question is: Yes, it is a form of multiple inheritance, because you can inherit behavior from different parents. What's missing is to inherit states, i. e., attributes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...