Home | | Object Oriented Programming | | The Complete Reference Java | | Internet Programming | | Web Programming | Use Java static Methods in an Interface

Chapter: Java The Complete Reference - The Java Language - Packages and Interfaces

| Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail |

Use Java static Methods in an Interface

JDK 8 added another new capability to interface: 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.

Use static Methods in an Interface

 

JDK 8 added another new capability to interface: 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. Here is the general form:

 

InterfaceName.staticMethodName

 

Notice that this is similar to the way that a static method in a class is called.

 

The following shows an example of a static method in an interface by adding one to MyIF, shown in the previous section. The static method is getDefaultNumber( ). It returns zero.

 

public interface MyIF {

 

     This is a "normal" interface method declaration.

 

     It does NOT define a default implementation. int getNumber();

 

     This is a default method. Notice that it provides

 

     a default implementation.

 

default String getString() { return "Default String";

}

// This is a static interface method. 

static int getDefaultNumber() {

 

return 0;

 

}

 

}

 

The getDefaultNumber( ) method can be called, as shown here:

 

int defNum = MyIF.getDefaultNumber();

 

As mentioned, no implementation or instance of MyIF is required to call getDefaultNumber( ) because it is static.

One last point: static interface methods are not inherited by either an implementing class or a subinterface.


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.