Skip to Content

Static methods in Interfaces with Java 8

Posted on 4 mins read

Java 8 is here! That was a long wait. I mean for people who like to wait for the thing to be fully released before they even try it. I know a lot of people who even think they need to wait until Java 9 is out to start to use Java 8. For me the wait for a little shorter since I’ve been using Java 8 for quite some time and even shipped apps with it. Small apps but real apps.

Anyway, let’s take a look at one of the new features that I really like. People talked a lot about default methods in interfaces. They are great! Another great thing is static methods in interfaces. I really love those.

Before Java 8

You remember those times where you had a Function interface and a Functions class with a bunch of static methods to create specific implementations of Function? Take a look at Guava code. It uses a lot this pattern. And we used to like it.

With Java 8

Now time has come to merge these two classes. We can put all static methods of Functions back into Function like this:

public interface Function<T, R> {
  R apply(T t);

  static Function<?, String> toStringFunction() {
    return value -> value.toString();
  }

  static <E> Function<E, E> identity() {
    return value -> value;
  }

  static <R> Function<?, R> constant(R constantValue) {
    return value -> constantValue;
  }
}
comments powered by Disqus