155. Checking default methods

Java 8 has enriched the concept of interfaces with default methods. These methods are written inside interfaces and have a default implementation. For example, the Slicer interface has a default method called slice():

public interface Slicer {

public void type();

default void slice() {
System.out.println("slice");
}
}

Now, any implementation of Slicer must implement the type() method and, optionally, can override the slice() method or rely on the default implementation.

The Java Reflection API can identify a default method via the Method.isDefault() flag method:

Class<Slicer> clazz = Slicer.class;
Method[] methods = clazz.getDeclaredMethods();

for (Method method: methods) {
System.out.println("Method name: " + method.getName()
+ ", is default? " + method.isDefault());
}

We will receive the following output:

Method name: type, is default? false
Method name: slice, is default? true
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.34.146