Home > Software design >  Why is static method(with implementation) used inside an interface? Why is the below interface made
Why is static method(with implementation) used inside an interface? Why is the below interface made

Time:06-30

public interface Validator {
static boolean checkEmptyOrNull(String string, ApiException apiException) {
    if (Objects.isNull(string) || string.trim().isEmpty()) {
        throw apiException;
    }
    return true;
}


static boolean checkEmptyOrNull(int value, ApiException apiException) {
    if (value < 1) {
        throw apiException;
    }

    return true;
}

}

Why haven't we just created a class instead of interface? What difference it would make?

CodePudding user response:

The static methods was included in Java 8.

Suppose we have the Product interface which is implemented in multiple classes, for that case we could add product operations directly in the interface, this allows to group responsibilities and reuse code, just that.

CodePudding user response:

The static methods in interfaces are similar to default methods but the difference is that you can’t override them.

A link to an old question (pre Java 8) but it has been updated to include this answer https://stackoverflow.com/a/513001/2310289

  • Related