Until now one could not add fully implemented method(s) to interfaces.
With Java 8 default methods this changes.
Default methods enable one to add new method(s) to previously defined
interfaces without breaking existing implementations of those interfaces
and ensuring backward compatibility.
We will now demonstrate the use of default method in an interface with
an example.
In this hypothetical example, the application will display the contact
information in an XML format.
The following is a simple interface for contact:
The following is a simple implementation of the interface for contact:
The following is a simple test application using the interface and the
implementation for contact:
Executing the program from Listing.3 will generate the following
output:
With time the requirements change and now there is a need for the
application to display the contact information in a JSON format as well.
The following is the modified simple interface for contact that uses a
default method:
Prior to Java 8, one would implement all the methods of an interface in
an implementation class. With Java 8, we can add the new capability
using the default method without breaking the existing class
MyContactTest.
In other words, the application MyContactTest will continue to work
without any code changes even though the interface Contact changed.
The following is a newer version of the test application using the
interface and the implementation for contact:
Executing the program from Listing.5 will generate the following
output:
The default methods can only access the methods defined in the
interface.
This may lead to the question - can one implement the methods from the
Object class such as equals(),
hashCode(), or toString()
?
The answer is NO !!!
!!! ATTENTION !!!
Trying to implement any of the methods such as equals(), hashCode(), or
toString(), will result in the following compiler error:
A default method cannot override a method from java.lang.Object
What happens when a class tries to implement two or more interfaces
that have default method(s) with the same name ?
Here is a simple example:
The code in Listing.8 will generate a compiler error. The way to fix
that is to override and implement the default method desc()
in the class ClsAB as shown below:
!!! ATTENTION !!!
When a class tries to implement two or more interfaces that have
default method(s) with the same name, it will result in the following
compiler error:
Duplicate default methods named desc with the parameters () and () are
inherited from the types IntB and IntA