Java Interface Static Method Tutorial

In this section, we will learn what the interface static method is and how to use it in Java.

Note: we’re assuming you’re already familiar with interfaces.

What is Static Method in Java Interface?

In Java interfaces, other than abstract methods, we can use static methods as well.

When a method is declared as static in an interface, its body should also be defined as well.

Basically, we can’t have a static abstract method in an interface!

The access specifier of a static method can be either `public` or `private`.

If the access specifier is `public`, the method can be called outside of the interface in other classes directly via the name of the interface.

But if the method is declared as `private` we can’t access the method anywhere other than inside the body of the interface itself.

Example: using static Method in Java Interface

public interface SecondInterface {
    private static void check(){
        System.out.println("Private static method of the FirstInterface ");
    }
    public static void c2(){
        SecondInterface.check();
    }
}

Here, the `check()` method is defined as static and `private`. So the method is only accessible inside the body of the interface itself.

On the other hand, the `c2()` method is `public` and so we can access this method outside in other classes as well.

Java Interface Static methods are not inheritable

This means we can’t use the name of a class that implemented the interface to access the static method.

Only via the name of the interface we can access its static methods.

How to Invoke Static Method of Java Interface?

As you saw in the previous example, we can use the name of the target interface to invoke a static method.

Example: invoking static method of Java interface

public interface FirstInterface {

    private static void check(){
        System.out.println("Private static method of the FirstInterface");
    }
    public static void c2(){
        FirstInterface.check();
    }
}

Now create a class named `Simple` and put the code below into that class:

public class Simple {
    public static void main(String[] args) {
        FirstInterface.c2();
    }
}

Output:

Private static method of the FirstInterface

Within the body of the `main()` method, we’ve called the `c2()` method of the `FirstInterface` interface and because the `c2()` is a public static method, it ran without any error.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies