Static Methods In Interface

Java-Static Methods In Interface

Static Methods In Interface

Another feature added to interface by JDK 8 is the ability to define one or more static methods. Like static methods in a class, a static method defined by an interface can be called independently of any object. Thus, no implementation of the interface is necessary, and no instance of the interface is required, in order to call a static method. Instead, a static method is called by specifying the interface name, followed by a period, followed by the method name( InterfaceName.staticMethodName( ) ). This is similar to the way that a static method in a class is called.

The following program shows an example of a static method in an interface by adding one to Speed interface. The static method is safeSpeed( ). The safeSpeed( ) method can be called by interface name, no implementation or instance of Speed is required to call safeSpeed( ) because it is static. Static interface methods are not inherited by either an implementing class or a subinterface.

Program

Static Methods In Interface Static Methods In Interfaces

Program Source

interface Speed {
    
    default void topSpeed() {
        
        System.out.println("defaultMethod");
    }
    static void safeSpeed() {
        
        System.out.println("Safe Speed : 80-90 km/h");
    }
}
public class Javaapp {

    public static void main(String[] args) {
        
        Speed.safeSpeed();
    }
}

Leave a Comment