Static Interface Methods

Since Java 8, authors have introduced support for static methods within interfaces. This methods are defined explicitly with the static keyword and function nearly identically to static methods defined in classes. In fact, there is really only one distinction between a static method in a class and in interface – a static method defined in an interface is not inherited in any classes that implement the interface.

Here are the static interface method rules developers need to be familiar with :

  • Like all methods in an interface, a static method is assumed to be public and will not compile if marked as private or protected
  • To reference the static method, a reference to the name of the interface must be used

The following is an example of a static method defined in an interface :

public interface Hop {
static int getJumpHeight() {
return 8;
}
}

The method getJumpHeight() in the example above works just like a static method as defined in a class. In other words, it can be accessed without an instance of the class using the Hop.getJumpHeight() syntax. Also, the compiler will automatically insert the access modifier public since all methods in interfaces are assumed to be public.

The following is an example of a class Bunny that implements Hop :

public class Bunny implements Hop {
public void printDetails() {
System.out.println(getJumpHeight()); // DOES NOT COMPILE
}
}

Without an explicit reference to the name of the interface the code will not compile, even though Bunny implements Hop. As it was mentioned above, static interface methods are not inherited by a class implementing the interface. The following modified version of the code resolves this issue with a reference to the interface name Hop :

public class Bunny implements Hop {
public void printDetails() {
System.out.println(Hop.getJumpHeight());
}
}

It follows, then, that a class that implements two interfaces containing static methods with the same signature will still compile at runtime, because the static methods are not inherited by the subclass and must be accessed with the reference to the interface name. It contrasts with the behavior of Default Interface Methods. Static Interface Methods don’t face multiple inheritance issues and rules as Default Interface Methods do.

Leave a Reply

Your email address will not be published. Required fields are marked *