Learnitweb

static methods in interface

In Java 8, you can define static methods in interfaces. The use of static methods is to write helper methods. A static method is associated with the class in which it is defined rather than the object of that class.

Java 8 has introduced static methods in interfaces. Now you can define static methods specific to an interface in the same interface rather than in a separate class.

You can define a static method in an interface using static keyword at the beginning of the method signature. static method in interface are by default public, so it is optional to use public modifier.

Need for static method in interface

Prior to Java 8, if you had an interface Foo and if you wanted to group interface related helper or util methods, you would need to create a separate class FooUtils. And if you wanted to restrict the way your FooUtils class is used, you would have to make it final and make its constructor private.

Now, with the introduction of static methods in Java 8, you can keep your utility methods related to interface in the interface itself without creating additional class.

Defining static method in interface and its use

You define a static method in interface using static keyword at the beginning of the method signature. In the following Foo interface, helper() is a static method.

interface Foo {
	public static void helper() {
		System.out.println("inside helper method");
	}
}

You can call helper method of Foo interface using interface name like Foo.helper();

public class Test {
	public static void main(String args[]) {
		Foo.helper();
	}
}

Note that static method defined in interface are not available to class implementing the interface with static method. Let’s try to call helper method.

public class Test implements Foo {
	public static void main(String args[]) {
		Test t = new Test();
		t.helper(); //Not allowed
		Test.helper(); // Not allowed
	}
}

You will get compile time error like this:

Test.java:10: error: cannot find symbol
                t.helper(); //Not allowed
                 ^
  symbol:   method helper()
  location: variable t of type Test
Test.java:11: error: cannot find symbol
                Test.helper(); // Not allowed
                    ^
  symbol:   method helper()
  location: class Test
2 errors

Note:

Since static method of interface are not accessible to class implementing that interface, there is no case of overriding the method. So class implementing interface with static method can:

  • Define a new method with same signature.
  • Define a new method with same name but with more restricted (private) modifier.
  • Define a new non static method with same name.