Java 8 – Static and Default Methods in Interface2 min read

Java 8

Overview

An Interface in Java has evolved a lot since it was first introduced in Java 1.0 and now with Java 8, we can even implement Static and Default methods inside our Interface.

Let’s take a look at the Java 8 implementation of both these methods;

1. Static Method

Static method in an Interface is implemented in the same way it is done in a concrete class, by default access specifier is Public and there is no restriction on the number of Static methods we can have inside an Interface. For example:

interface InterfaceHavingStaticMethod {

    static int getHashCode(String input) {
        return input.hashCode();
    }
}

Here, we have defined a static method named getHashCode(String input) which returns an equivalent hashCode for every String passed.

There are a couple of benefits of using Static methods:

  • Static methods can be a good alternative to utility classes, for example sorting, null check function etc. can be easily defined through it.
  • It also adds to security, as its functionality cannot be overridden by any of the implementation classes.

2. Default Method

Consider a Scenario, wherein you want to add a new functionality to your application, you cannot do it by adding it to the original interfaces, as then all the implementation classes have to be rewritten. Nor, you can add it using a Static Method, as it can be misunderstood as a utility method.
So, in situations like these, Default methods come into the picture.
Let’s take a look at the below code snippet:

@FunctionalInterface
interface InterfaceHavingStaticMethod {

    static int getHashCode(String input) {
        return input.hashCode();
    }

    default int getUniqueKey(int i, String s) {
        return id * getHashCode(name);
    }

    void abstractMethod(String s);
}

In the above code, we have defined getUniqueKey(int i, String s) method prefixed with default keyword, as our default method. By default, access specifier is public, also any class implementing the interface can override the default method implementation.

After understanding in brief about default methods, let’s summarize its benefits:

  • Also called as Defender Methods or Virtual extension methods, it helps us to add new functionality(just like the discussed scenario) to the interfaces of our older libraries, hence ensures compatibility.
  • Helps in providing default implementations to the generic requirements.

Conclusion

In this mini-article, we learned about:

  • Static methods and its advantages in Interface.
  • Default methods and its usages.

If you closely observed the above code snippet, you must have noticed @FunctionalInterface annotation, to know more about it, click here.

As usual, you can find the code on:
cec44feb-0b1b-4fe3-936d-67a51a1fe28e

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.