Default Methods in Interfaces
Only interfaces can define default methods. A default method is an instance method declared with the keyword default and whose implementation is provided by the interface. However, a default method in a top-level interface always has public access, whether the keyword public is specified or not.
default
return_type method_name
(
formal_parameter_list
)
throws_clause
{
implementaion_of_method_body
}
A class implementing an interface can optionally decide to override any default method in the interface, as can a subinterface of the interface. If a default method is not overridden to provide a new implementation, the default implementation provided by the interface is inherited by the class or the subinterface.
No other non-access modifiers, such as abstract, final, or static, are allowed in a default method declaration. A default method is not abstract because it provides an implementation; is not final because it can be overridden; and is not static because it can be invoked only on instances of a class that implements the interface in which the default method is declared.
Note that a default method can only be implemented in terms of the values of its local variables (including those passed as parameters) and calls to other methods accessible in the interface, but without reference to any persistent state, as there is none associated with an interface.
The keyword default in the context of a default method should not be confused with default or package accessibility of a method in a class, which is implied in the absence of any access modifier.
Example 5.11 illustrates the use of default methods. The default method printSlogan() at (1) in the interface ISlogan is overridden at (2) in the class JavaGuru, and is inherited by the class JavaGeek at (3). The output from the program shows that this is the case.
Example 5.11 Default Methods in Interfaces
// File: JavaParty.java
interface ISlogan {
default void printSlogan() { // (1)
System.out.println(“Happiness is getting certified!”);
}
}
//_______________________________________________________________________________
class JavaGuru implements ISlogan {
@Override
public void printSlogan() { // (2) overrides (1)
System.out.println(“Happiness is catching all the exceptions!”);
}
}
//_______________________________________________________________________________
class JavaGeek implements ISlogan { } // (3) inherits (1)
//_______________________________________________________________________________
public class JavaParty {
public static void main(String[] args) {
JavaGuru guru = new JavaGuru();
guru.printSlogan(); // (4)
JavaGeek geek = new JavaGeek();
geek.printSlogan(); // (5)
}
}
Output from the program:
Happiness is catching all the exceptions!
Happiness is getting certified!