Skip to content

Java 8 Interface With Static Method#

Definition#

  • Java interface static method is similar to default method except that we can not override them in the implementation classes. This feature helps us in avoiding undesired results in case of poor implementation in implementation classes.

  • Java interface static method is part of interface, we can not use it for implementation class objects.

  • Java interface static methods are good for providing utility methods, for example null check, collection sorting etc.
  • Java interface static method helps us in providing security by not allowing implementation classes to override them.
  • We can not define static method in methods of object class, then we can get the error "this static method can not hide the instance method from Object". This is no acceptable in java, when object is a base class for all classes, we can not have a static method and other method with the same format.
  • We can use static methods to remove utility methods as Collections and make methods can connect to interface then we can easily find and use these methods.

Example#

SampleStaticInterface.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package com.java.core.staticmethodinterface;

public interface SampleStaticInterface {

    default void print(String string) {
        if(!isNull(string)) {
            System.out.println("SampleStaticInterface print: " + string);
        }
    }

    static boolean isNull(String str) {
        System.out.println("SampleStaticInterface null check");
        return str == null || ("".equals(str));
    }

}
MyImpl.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
package com.java.core.staticmethodinterface;

public class MyImpl implements SampleStaticInterface {

    public boolean isNull(String str) {
        System.out.println("MyImpl null check: " + str);
        return str == null;
    }

}
JavaStaticMethodInterfaceMain.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
package com.java.core.staticmethodinterface;

//test
public class JavaStaticMethodInterfaceMain {

    public static void main(String[] args) {
        MyImpl myImpl = new MyImpl();
        myImpl.print("Expect null check from static method interface!");
        myImpl.isNull("Expect null check from MyImpl!");
    }

}
  • Then we can see the results in the log as below:
SampleStaticInterface null check
SampleStaticInterface print: Expect null check from static method interface!
MyImpl null check: Expect null check from MyImpl!

Process finished with exit code 0
  • If we make the interface method from static to default, we will get following output:
MyImpl null check: Expect null check from static method interface!
SampleStaticInterface print: Expect null check from static method interface!
MyImpl null check: Expect null check from MyImpl!

Process finished with exit code 0

References#