Static Interface Method in Java8

This article explains static interface methods added as part of Java.

 

Static Methods in an Interface

 

JDK 8 added the ability to define one or more static methods in an interface.

 

Since its static, a static method defined by an interface can be called independent of any object. So, no implementation of the interface is required for calling the static method.

 

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

 

Here is an example of an interface static method :

 

public interface InterfaceWithStaticMethod {

  static String getDefaultString(){
    return "hello";
  }
}


 

A static interface method can be accessed using the Interface name.

 

Here is the general syntax of accessing an Interface static method :

InterfaceName . staticMethodName

 

Here is the code for a class accessing this static interface method :

 

public class StaticInterfaceMethodDemo {

  public static void main(String[] args) {
    System.out.println(InterfaceWithStaticMethod.getDefaultString());
  }

}


 

This program calls the static method getDefaultString() using the interface name InterfaceWithStaticMethod.

 

The output of the above program will be :

hello

 

 

© 2015, https:. All rights reserved. On republishing this post, you must provide link to original post

You may also like...

Leave a Reply.. code can be added in <code> </code> tags