1
public interface Example<E>
{
    E get(int index);

    default E get()
    {
        return get(0);
    }
}

This would be the initial design of the interface. Is something like this an acceptable use of a default method (basically for default arguments), or should they only be used in the future for added functionality?

sep1256
  • 55
  • 6
  • 1
    The official line I've heard from Oracle is that it's primarily intended for future added functionality. But there are interfaces new in Java 8 that include default methods, so it looks like they don't take their own advice. :) – yshavit Feb 15 '17 at 21:02
  • 4
    This looks fine to me; I wouldn't have problems with this at code review. Only comment would be naming - maybe `getFirst`? Also would need to document that it will `throw` something if the thing is empty - which brings me to my final point; this doesn't compile - missing the name on the `interface` declaration. – Boris the Spider Feb 15 '17 at 21:07
  • You can add the default method tomorrow, when it is the future :) – ZhongYu Feb 15 '17 at 21:08
  • @ZhongYu but by then it will be today. _Dilemma!_ – Boris the Spider Feb 15 '17 at 21:09
  • A default method should document its behavior, usually just repeating the default method body. But that behavior isn't necessarily the contract of the method. – ZhongYu Feb 15 '17 at 21:11

3 Answers3

2

That is a valid use of the default method on an interface in Java 8 and newer.

Here is the docs: https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html

And tutorial: http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/JavaSE8DefaultMethods/JavaSE8DefaultMethods.html

AlexC
  • 1,395
  • 14
  • 26
1

The official sources that I could find from Oracle about the intended usage of default interface method is (source):

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.

However, I treat it as being the same as an abstract class, defining abstract methods that must be implemented by subclasses (in this case, interface methods without default implementation), as well as providing concrete methods that may be overriden by subclasses (default interface method).

JChrist
  • 1,734
  • 17
  • 23
1

It's officially stated purpose is for backwards compatibility with clients implementing the old interface (otherwise they would all have to go back and implement this new method). It was only added for this purpose and not originally a feature of Java. But honestly, it's not a big deal and the added ease-of-use certainly makes it acceptable in my opinion.