Java8 allows interface to have static method. It would be really helpful if anybody explain in which scenario we might need to go for interface with static methods.
Thanks in advance.
Java8 allows interface to have static method. It would be really helpful if anybody explain in which scenario we might need to go for interface with static methods.
Thanks in advance.
Well did you search the jdk sources? How about at least two examples:
Function.identity()
that has an implementation as :
static <T> Function<T, T> identity() {
return t -> t;
}
Or Predicate.isEqual
that looks like:
static <T> Predicate<T> isEqual(Object targetRef) {
return (null == targetRef)
? Objects::isNull
: object -> targetRef.equals(object);
}
Generally I treat them as static factory methods that return an instance of that interface back.
I have a great example of this that we use in our code base (but it comes from Holger initially):
public interface UncheckedCloseable extends Runnable, AutoCloseable {
@Override
default void run() {
try {
close();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
static UncheckedCloseable wrap(AutoCloseable c) {
return c::close;
}
default UncheckedCloseable nest(AutoCloseable c) {
return () -> {
try (UncheckedCloseable c1 = this) {
c.close();
}
};
}
}
Resource can be found here and here:
From what I have understood-
1.These methods cannot be overridden by classes that inherit it.
2.They are accessible only to the functions of that interface(must not be overridden).
So, they can be used whenever you want that the function(which is not static nor overridden) of your interface to use that function(which is static).
So you can use your own business logic in it, your own sorting methods, some limitations or boundations.
So it can be used as if someone calls your function and you do your own stuff in it with help of other functions. It is like that the other programmer implements your interface to use some function that provides some support to its own program(eg. calendar that can save notes, plan your meetings, etc).
But remember you should not have overridden the function that calls those static function.