Java Reference
In-Depth Information
utility classes along with interfaces. From Java 8, you can have static methods in interfaces. A static method contains
the static modifier. They are implicitly public. You can redefine the Walkable interface as shown in Listing 17-9 to
include the letThemWalk() method and get rid of the Walkables class altogether.
Listing 17-9. The Revised Walkable Interface with an Additional Static Convenience Method
// Walkable.java
package com.jdojo.interfaces;
public interface Walkable {
// An abstract method
void walk();
// A static convenience method
public static void letThemWalk(Walkable[] list) {
for (int i = 0; i < list.length; i++) {
list[i].walk();
}
}
}
You can use the static methods of an interface using the dot notation.
<interface-name>.<static-method>
The following snippet of code calls the Walkable.letThemWalk() method:
Walkable[] w = new Walkable[4];
w[0] = new Person("Jack");
w[1] = new Duck("Jeff");
w[2] = new Person("John");
w[3] = new Cat("Jace");
// Let everyone walk
Walkable.letThemWalk(w);
Jack (a person) is walking.
Jeff (a duck) is walking.
John (a person) is walking.
Jace (a cat) is walking.
Unlike static methods in a class, static methods in an interface are not inherited by implementing classes or
subinterfaces. An interface that inherits from another interface is called a subinterface. There is only one way to call
the static methods of an interface: by using the interface name. A static method m() of an interface I must be called
using I.m() . You can use the unqualified name m() of the method to call it only within the body of the interface or
when you import the method using a static import statement.
Default Methods Declarations
A default method in an interface is declared with the modifier default. A default method provides a default
implementation for the classes that implements the interface, but does not override the default method.
Search WWH ::




Custom Search