Can interfaces have Static methods in Java?


An interface in Java is similar to class but, it contains only abstract methods and fields which are final and static.

A static method is declared using the static keyword and it will be loaded into the memory along with the class. You can access static methods using class name without instantiation.

Static methods in an interface since java8

Since Java8 you can have static methods in an interface (with body). You need to call them using the name of the interface, just like static methods of a class.

Example

In the following example, we are defining a static method in an interface and accessing it from a class implementing the interface.

 Live Demo

interface MyInterface{
   public void demo();
   public static void display() {
      System.out.println("This is a static method");
   }
}
public class InterfaceExample{
   public void demo() {
      System.out.println("This is the implementation of the demo method");
   }
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      obj.demo();
      MyInterface.display();
   }
}

Output

This is the implementation of the demo method
This is a static method

Updated on: 29-Jun-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements