In Java 8, interfaces were enhanced with the ability to contain static methods. Unlike abstract or default methods, static methods in interfaces have a complete implementation and cannot be overridden by implementing classes.
Key Features
- Declared with the static keyword inside an interface.
- Contain a complete definition and cannot be overridden.
- Called using the interface name only (e.g., InterfaceName.methodName()).
- The scope of the static method is limited to the interface in which it is defined.
Example 1: Java program to demonstrate a static method in an Interface.
interface NewInterface {
// static method
static void hello()
{
System.out.println("Hello, New Static Method Here");
}
// Public and abstract method of Interface
void overrideMethod(String str);
}
// Implementation Class
public class InterfaceDemo implements NewInterface {
public static void main(String[] args)
{
InterfaceDemo interfaceDemo = new InterfaceDemo();
// Calling the static method of interface
NewInterface.hello();
// Calling the abstract method of interface
interfaceDemo.overrideMethod("Hello, Override Method here");
}
// Implementing interface method
@Override
public void overrideMethod(String str)
{
System.out.println(str);
}
}
Output
Hello, New Static Method Here Hello, Override Method here
Example 2: Scope of Static Method
Java program to demonstrate scope of static method in Interface.
interface PrintDemo {
// Static Method
static void hello()
{
System.out.println("Called from Interface PrintDemo");
}
}
public class InterfaceDemo implements PrintDemo {
public static void main(String[] args)
{
// Call Interface method as Interface name is preceding with method
PrintDemo.hello();
// Call Class static method
hello();
}
// Class Static method is defined
static void hello()
{
System.out.println("Called from Class");
}
}
Output
Called from Interface PrintDemo Called from Class
