Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

Default methods and binary compatibility

James_DMar 25 2014

The documentation for default methods says

"Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces."

Is this really true? If an existing class implements my interface, and also another interface that also happens to define a default method with the same signature as the one I introduce, then that class will break.

Specifically, suppose I am the author of an existing interface

public interface A {

}

If I update it to include a default method:

public interface A {

    public default int getAnswer() {

        return 42 ;

   }

}

then if there happens to be a class out there implementing both my interface and another which already defines the same default method:

public interface B {

    public default int getAnswer() {

        return 6 * 9 ;

    }

}

public class C implements A, B {

    public static void main(String[] args) {

        System.out.println(new C().getAnswer());

    }

}

then my changes to A break the existing class C in the worst possible way: the previously compiled version of C will now throw a runtime exception.

In what sense do the changes to A "ensure binary compatibility with code written for older versions of [A]"?

I also posted this question at StackOverflow, but without any satisfactory answer.

Comments

Post Details

Added on Mar 25 2014
0 comments
860 views