Static Methods in Java Interface

In the post Default Methods in Java Interface we have already seen one of the added feature in interface in Java- Interface default methods. In this post we’ll see another feature added to the interfaces in Java 8- Static method in Java interface.

Interface static methods in Java

As you must be knowing a static method is a method associated with the class in which it is defined rather than with any object. Every instance of the class shares its static methods.

Same static method functionality stands true for static methods in interfaces too. A static method is associated with an interface in which it is defined, static method can be called independently of any object. So, you don’t need to implement the interface or get the instance of the interface in order to invoke an interface static method.

To define a static method in Java interface you add static keyword at the beginning of the method signature which is similar to how you define static methods in Java classes.

All methods in the Java interface are implicitly public so static methods in interfaces are also public by default.

To invoke a static method in an interface you use the following syntax-

Java Interface static method example

Output

As you can see to access the static method getDate() in the interface the class doesn’t need to implement the interface.

Benefits of interface static methods

  1. Generally static methods are used to write helper (utility) methods, so these helper methods can be written in an interface now.
  2. Keeping static methods in an interface makes it easier for you to organize helper methods in your libraries. You can keep static methods specific to an interface in the same interface rather than in a separate class, for example Collection interface and Collections class.

Interface static methods are not inherited

Static methods in an interface are not inherited either by any extending interface or by an implementing class.

Trying to inherit static method in an extending interface.

interface static method in Java
From extending interface you are trying to access the static method in the super interface which results in compile time error.

A class implementing an interface also can’t access the static method of the interface using class name.

static method in interface

That’s all for the topic Static Methods in Java Interface. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

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

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