Java 8 Feature – Static Methods in Interface

Java 8 introduced the capability for writing Static methods in an Interface.

Static method in interface can be written using static keyword. These methods can be accessed directly by Interface name itself without instantiating it.

Classes which are implementing the interface with static method/ methods can use the static methods with InterfaceName.

This feature is very helpful for writing utility / helper methods.

Syntax for calling Static Method of Interface –

InterfaceName.StaticMethodName();

Example –

Java Program –

package com.thinkconstructive;

interface StaticInterfaceExample
{
    static void printMessage()
    {
        System.out.println("This is Static Method in Interface");
    }
}

public class DemoStatic {
    public static void main(String args[])
    {
        StaticInterfaceExample.printMessage();
    }
}

Output of the above program –

This is Static Method in Interface

In the above example, StaticInterfaceExample is an Interface which has a static method named as printMessage() with respective implementation.

printMessage() method is called in main class as StaticInterfaceExample.printMessage() . It is to be noticed that no instance is created rather, static method is directly called with the Interface name.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *