Static Methods in Interface are those methods, which are defined in the interface with the keyword static. Unlike other methods in Interface, these static methods contain the complete definition of the function and since the definition is complete and the method is static, therefore these methods cannot be overridden or changed in the implementation class.
Similar to Default Method in Interface, the static method in an interface can be defined in the interface, but cannot be overridden in Implementation Classes. To use a static method, Interface name should be instantiated with it, as it is a part of the Interface only.
Below programs illustrate static methods in interfaces:
Program 1: To demonstrate use of Static method in Interface.
In this program, a simple static method is defined and declared in an interface which is being called in the main() method of the Implementation Class InterfaceDemo. Unlike the default method, the static method defines in Interface hello(), cannot be overridden in implementing the class.
Java
interface NewInterface {
static void hello()
{
System.out.println( "Hello, New Static Method Here" );
}
void overrideMethod(String str);
}
public class InterfaceDemo implements NewInterface {
public static void main(String[] args)
{
InterfaceDemo interfaceDemo = new InterfaceDemo();
NewInterface.hello();
interfaceDemo.overrideMethod( "Hello, Override Method here" );
}
@Override
public void overrideMethod(String str)
{
System.out.println(str);
}
}
|
Output:
Hello, New Static Method Here
Hello, Override Method here
Program 2: To demonstrate Scope of Static method.
In this program, the scope of the static method definition is within the interface only. If same name method is implemented in the implementation class then that method becomes a static member of that respective class.
Java
interface PrintDemo {
static void hello()
{
System.out.println( "Called from Interface PrintDemo" );
}
}
public class InterfaceDemo implements PrintDemo {
public static void main(String[] args)
{
PrintDemo.hello();
hello();
}
static void hello()
{
System.out.println( "Called from Class" );
}
}
|
Output:
Called from Interface PrintDemo
Called from Class
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!