Java 1.8 interface static method is visible to interface methods only, if we remove the methodSta1() method from the InterfaceExample class,
we won’t be able to use it for the InterfaceExample object. However like other static methods, we can use interface static methods using class name.
For example, a valid statement will be:
exp1.methodSta1();
So after looking below example we can say :
1) Java interface static method is part of interface, we can’t use it for implementation class objects.
2) Java interface static methods are good for providing utility methods, for example null check, collection sorting ,log etc.
3) Java interface static method helps us in providing security by not allowing implementation classes (InterfaceExample) to override them.
4) We can’t define interface static method for Object class methods, we will get compiler error as “This static method cannot hide the instance method from Object”. This is because it’s not allowed in java, since Object is the base class for all the classes and we can’t have one class level static method and another instance method with same signature.
5) We can use java interface static methods to remove utility classes such as Collections and move all of it’s static methods to the corresponding interface,
that would be easy to find and use.
public class InterfaceExample implements exp1 {
@Override
public void method() {
System.out.println("From method()");
}
public static void main(String[] args) {
new InterfaceExample().method2();
InterfaceExample.methodSta2();
exp1.methodSta1();
}
static void methodSta2() {
System.out.println("========= InterfaceExample :: from methodSta2() ======");
}
}
interface exp1 {
void method();
static void methodSta1() {
System.out.println("========= exp1:: from methodSta1() ======");
}
static void methodSta2() {
System.out.println("========= exp1:: from methodSta2() ======");
}
default void method2() { System.out.println("--- exp1:: from method2() ---");}
}